diff --git a/src/Concerns/Persist.php b/src/Concerns/Persist.php index 4eb53180..a16484ba 100644 --- a/src/Concerns/Persist.php +++ b/src/Concerns/Persist.php @@ -11,12 +11,16 @@ trait Persist { public array $persist = []; + public string $persistPrefix = ''; + /** - * $tableItems: 'filters', 'columns', 'sorting' + * $tableItems: 'filters', 'columns', 'sorting', + * $prefix: Add prefix to the persist storage key */ - public function persist(array $tableItems): PowerGridComponent + public function persist(array $tableItems, string $prefix = ''): PowerGridComponent { - $this->persist = $tableItems; + $this->persist = $tableItems; + $this->persistPrefix = $prefix; return $this; } @@ -51,11 +55,10 @@ protected function persistState(string $tableItem): void return; } - if ($this->getPersistDriverConfig() === 'session') { - Session::put('pg:' . $this->tableName, strval(json_encode($state))); - } elseif ($this->getPersistDriverConfig() === 'cookies') { - Cookie::queue('pg:' . $this->tableName, strval(json_encode($state)), now()->addYears(5)->unix()); - } + match ($this->getPersistDriverConfig()) { + 'session' => Session::put($this->getPersistKeyName(), strval(json_encode($state))), + default => Cookie::queue($this->getPersistKeyName(), strval(json_encode($state)), now()->addYears(5)->unix()) + }; } /** @@ -67,21 +70,12 @@ private function restoreState(): void return; } - $cookieOrSession = null; - - if ($this->getPersistDriverConfig() === 'session') { - /** @var null|string $cookieOrSession */ - $cookieOrSession = Session::get('pg:' . $this->tableName); - } elseif ($this->getPersistDriverConfig() === 'cookies') { - /** @var null|string $cookieOrSession */ - $cookieOrSession = Cookie::get('pg:' . $this->tableName); - } - - if (is_null($cookieOrSession)) { - return; - } + $storage = match ($this->getPersistDriverConfig()) { + 'session' => Session::get($this->getPersistKeyName()), + default => Cookie::get($this->getPersistKeyName()) + }; - $state = (array) json_decode(strval($cookieOrSession), true); + $state = (array) json_decode(strval($storage), true); if (in_array('columns', $this->persist) && array_key_exists('columns', $state)) { $this->columns = collect($this->columns)->map(function ($column) use ($state) { @@ -119,4 +113,13 @@ private function getPersistDriverConfig(): string return $persistDriver; } + + private function getPersistKeyName(): string + { + if (!empty($this->persistPrefix)) { + return 'pg:' . $this->persistPrefix . '-' . $this->tableName; + } + + return 'pg:' . $this->tableName; + } }