|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace BlueFeather\EloquentFileMaker\Database\Eloquent\Concerns; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Cache; |
| 6 | + |
| 7 | +trait FMGuardsAttributes |
| 8 | +{ |
| 9 | + |
| 10 | + /** |
| 11 | + * Determine if the given key is guarded. |
| 12 | + * |
| 13 | + * @param string $key |
| 14 | + * @return bool |
| 15 | + */ |
| 16 | + public function isGuarded($key) |
| 17 | + { |
| 18 | + if (empty($this->getGuarded())) { |
| 19 | + return false; |
| 20 | + } |
| 21 | + |
| 22 | + return $this->getGuarded() == ['*'] || |
| 23 | + !empty(preg_grep('/^' . preg_quote($key) . '$/i', $this->getGuarded())) || |
| 24 | + !$this->isGuardableColumn($key); |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Determine if the given column is a valid, guardable column. |
| 29 | + * |
| 30 | + * @param string $key |
| 31 | + * @return bool |
| 32 | + */ |
| 33 | + protected function isGuardableColumn($key) |
| 34 | + { |
| 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); |
| 50 | + |
| 51 | + if (empty($columns)) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + static::$guardableColumns[get_class($this)] = $columns; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + protected function getColumns($forceRefresh = false): array |
| 60 | + { |
| 61 | + $cacheKey = "eloquent-filemaker-{$this->table}-columns"; |
| 62 | + $refreshCallback = function() { |
| 63 | + $layoutMetaData = $this->getConnection()->getLayoutMetadata($this->table); |
| 64 | + |
| 65 | + return array_column($layoutMetaData['fieldMetaData'], 'name'); |
| 66 | + }; |
| 67 | + |
| 68 | + if($forceRefresh) { |
| 69 | + Cache::forever($cacheKey, $columns = $refreshCallback()); |
| 70 | + |
| 71 | + return $columns; |
| 72 | + } |
| 73 | + |
| 74 | + return Cache::rememberForever($cacheKey, $refreshCallback); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments