| Total Complexity | 11 |
| Total Lines | 62 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 10 | final class SimpleCacheSchemaProvider implements SchemaProviderInterface |
||
| 11 | { |
||
| 12 | public const DEFAULT_KEY = 'Cycle-ORM-Schema'; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * @var non-empty-string |
||
|
|
|||
| 16 | */ |
||
| 17 | private string $key = self::DEFAULT_KEY; |
||
| 18 | |||
| 19 | 7 | public function __construct( |
|
| 20 | private CacheInterface $cache |
||
| 21 | ) { |
||
| 22 | 7 | } |
|
| 23 | |||
| 24 | /** |
||
| 25 | * Create a configuration array for the {@see self::withConfig()} method. |
||
| 26 | * @param non-empty-string $key |
||
| 27 | */ |
||
| 28 | 1 | public static function config(string $key): array |
|
| 29 | { |
||
| 30 | 1 | return [ |
|
| 31 | 1 | 'key' => $key, |
|
| 32 | 1 | ]; |
|
| 33 | } |
||
| 34 | |||
| 35 | 5 | public function withConfig(array $config): self |
|
| 36 | { |
||
| 37 | 5 | $new = clone $this; |
|
| 38 | 5 | $new->key = $config['key'] ?? self::DEFAULT_KEY; |
|
| 39 | 5 | return $new; |
|
| 40 | } |
||
| 41 | |||
| 42 | 4 | public function read(?SchemaProviderInterface $nextProvider = null): ?array |
|
| 43 | { |
||
| 44 | 4 | $schema = $this->cache->get($this->key); |
|
| 45 | |||
| 46 | 4 | if ($schema !== null || $nextProvider === null) { |
|
| 47 | 2 | return $schema; |
|
| 48 | } |
||
| 49 | |||
| 50 | 2 | $schema = $nextProvider->read(); |
|
| 51 | 2 | if ($schema !== null) { |
|
| 52 | 2 | $this->write($schema); |
|
| 53 | } |
||
| 54 | 2 | return $schema; |
|
| 55 | } |
||
| 56 | |||
| 57 | 3 | public function clear(): bool |
|
| 58 | { |
||
| 59 | 3 | if (!$this->cache->has($this->key)) { |
|
| 60 | 1 | return true; |
|
| 61 | } |
||
| 62 | 2 | $result = $this->cache->delete($this->key); |
|
| 63 | 2 | if ($result === false) { |
|
| 64 | 1 | throw new SchemaProviderException(\sprintf('Unable to delete `%s` from cache.', $this->key)); |
|
| 65 | } |
||
| 66 | 1 | return true; |
|
| 67 | } |
||
| 68 | |||
| 69 | 2 | private function write(array $schema): bool |
|
| 72 | } |
||
| 73 | } |
||
| 74 |