Skip to content

Commit

Permalink
Added Persist prefix (#1525)
Browse files Browse the repository at this point in the history
* Added Persist prefix

* refactor

---------

Co-authored-by: luanfreitasdev <luanfreitas10@protonmail.com>
  • Loading branch information
marcheffels and luanfreitasdev committed May 6, 2024
1 parent c855c70 commit 02834d3
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions src/Concerns/Persist.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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())
};
}

/**
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 02834d3

Please sign in to comment.