Issues (6)

src/SimpleCacheSchemaProvider.php (2 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Provider;
6
7
use Cycle\Schema\Provider\Exception\SchemaProviderException;
8
use Psr\SimpleCache\CacheInterface;
9
10
final class SimpleCacheSchemaProvider implements SchemaProviderInterface
11
{
12
    public const DEFAULT_KEY = 'Cycle-ORM-Schema';
13
14
    /**
15
     * @var non-empty-string
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
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
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
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
70
    {
71 2
        return $this->cache->set($this->key, $schema);
72
    }
73
}
74