Skip to content

Commit 02aaa21

Browse files
author
Michael Deck
committed
Add cache to guarded check
1 parent df48378 commit 02aaa21

File tree

1 file changed

+35
-13
lines changed

1 file changed

+35
-13
lines changed

src/Database/Eloquent/Concerns/FMGuardsAttributes.php

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
namespace BlueFeather\EloquentFileMaker\Database\Eloquent\Concerns;
44

5+
use Illuminate\Support\Facades\Cache;
6+
57
trait FMGuardsAttributes
68
{
79

810
/**
911
* Determine if the given key is guarded.
1012
*
11-
* @param string $key
13+
* @param string $key
1214
* @return bool
1315
*/
1416
public function isGuarded($key)
@@ -18,38 +20,58 @@ public function isGuarded($key)
1820
}
1921

2022
return $this->getGuarded() == ['*'] ||
21-
! empty(preg_grep('/^'.preg_quote($key).'$/i', $this->getGuarded())) ||
22-
! $this->isGuardableColumn($key);
23+
!empty(preg_grep('/^' . preg_quote($key) . '$/i', $this->getGuarded())) ||
24+
!$this->isGuardableColumn($key);
2325
}
2426

2527
/**
2628
* Determine if the given column is a valid, guardable column.
2729
*
28-
* @param string $key
30+
* @param string $key
2931
* @return bool
3032
*/
3133
protected function isGuardableColumn($key)
3234
{
33-
if (! isset(static::$guardableColumns[get_class($this)])) {
34-
$columns = $this->getColumns();
35+
$this->primeGuardableColumns();
36+
37+
if(in_array($key, static::$guardableColumns[get_class($this)])) {
38+
return true;
39+
}
40+
41+
$this->primeGuardableColumns(true);
42+
43+
return in_array($key, static::$guardableColumns[get_class($this)]);
44+
}
45+
46+
protected function primeGuardableColumns($forceRefresh = false)
47+
{
48+
if (!isset(static::$guardableColumns[get_class($this)])) {
49+
$columns = $this->getColumns($forceRefresh);
3550

3651
if (empty($columns)) {
3752
return true;
3853
}
3954
static::$guardableColumns[get_class($this)] = $columns;
4055
}
41-
42-
return in_array($key, static::$guardableColumns[get_class($this)]);
4356
}
4457

4558

59+
protected function getColumns($forceRefresh = false): array
60+
{
61+
$cacheKey = "{$this->table}-columns";
62+
$refreshCallback = function() {
63+
$layoutMetaData = $this->getConnection()->getLayoutMetadata($this->table);
4664

47-
protected function getColumns(): array{
48-
$layoutMetaData = $this->getConnection()->getLayoutMetadata($this->table);
49-
$fieldMetaData = $layoutMetaData['fieldMetaData'];
50-
$columns = array_column($fieldMetaData, 'name');
65+
return array_column($layoutMetaData['fieldMetaData'], 'name');
66+
};
67+
68+
if($forceRefresh) {
69+
Cache::forever($cacheKey, $columns = $refreshCallback());
70+
71+
return $columns;
72+
}
5173

52-
return $columns;
74+
return Cache::rememberForever($cacheKey, $refreshCallback);
5375
}
5476

5577
}

0 commit comments

Comments
 (0)