diff --git a/src/StorageDrivers/DatabaseStorageDriver.php b/src/StorageDrivers/DatabaseStorageDriver.php index d69f6071..1f4c93d4 100644 --- a/src/StorageDrivers/DatabaseStorageDriver.php +++ b/src/StorageDrivers/DatabaseStorageDriver.php @@ -53,27 +53,12 @@ class DatabaseStorageDriver implements StorageDriver public function get(string $uuid, string $key) { - $tenant = Tenant::find($uuid); - - return $tenant->$key ?? json_decode($tenant->data)[$key] ?? null; + return Tenant::find($uuid)->get($key); } public function getMany(string $uuid, array $keys): array { - // todo move this logic to the model? - $tenant = Tenant::find($uuid); - $tenant_data = null; // cache - json_decode() can be expensive - $get_from_tenant_data = function ($key) use ($tenant, &$tenant_data) { - $tenant_data = $tenant_data ?? json_decode($tenant->data); - - return $tenant_data[$key] ?? null; - }; - - return array_reduce($keys, function ($keys, $key) use ($tenant, $get_from_tenant_data) { - $keys[$key] = $tenant->$key ?? $get_from_tenant_data($key) ?? null; - - return $keys; - }, []); + return Tenant::getMany($keys); } public function put(string $uuid, string $key, $value) diff --git a/src/Tenant.php b/src/Tenant.php index 9e52a9c3..573ccad2 100644 --- a/src/Tenant.php +++ b/src/Tenant.php @@ -10,6 +10,58 @@ class Tenant extends Model protected $specialColumns = []; protected $guarded = []; + /** + * Decoded data from the data column. + * + * @var object + */ + private $dataObject; + + /** + * Get data from the data column. + * + * @param string $key + * @return mixed + */ + public function getFromData(string $key) + { + $this->dataObject = $this->dataObject ?? json_decode($this->{$this->dataColumn}); + return $this->dataObject->$key; + } + + /** + * Get data from tenant storage. + * + * @param string $key + * @return mixed + */ + public function get(string $key) + { + return $this->$key ?? $this->getFromData($key) ?? null; + } + + /** + * Get multiple values from tenant storage. + * + * @param array $keys + * @return array + */ + public function getMany(array $keys): array + { + return array_reduce($keys, function ($keys, $key) { + $keys[$key] = $this->get($key); + + return $keys; + }, []); + } + + /** + * Put data into tenant storage. + * + * @param string $key + * @param mixed $value + * @return mixed + */ public function put(string $key, $value) { if (array_key_exists($key, $this->specialColumns)) {