Passed
Pull Request — master (#82)
by Aleksei
09:10
created

SimpleCacheSchemaProvider::read()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 10
cc 4
nc 3
nop 1
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Schema\Provider;
6
7
use Psr\SimpleCache\CacheInterface;
8
use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface;
9
10
final class SimpleCacheSchemaProvider implements SchemaProviderInterface
11
{
12
    public const DEFAULT_KEY = 'Cycle-ORM-Schema';
13
    private CacheInterface $cache;
14
    private string $key = self::DEFAULT_KEY;
15
16 7
    public function __construct(CacheInterface $cache)
17
    {
18 7
        $this->cache = $cache;
19 7
    }
20
21 4
    public function withConfig(array $config): self
22
    {
23 4
        $new = clone $this;
24 4
        $new->key = $config['key'] ?? self::DEFAULT_KEY;
25 4
        return $new;
26
    }
27
28 4
    public function read(?SchemaProviderInterface $nextProvider = null): ?array
29
    {
30 4
        $schema = $this->cache->get($this->key);
31
32 4
        if ($schema !== null || $nextProvider === null) {
33 2
            return $schema;
34
        }
35
36 2
        $schema = $nextProvider->read();
37 2
        if ($schema !== null) {
38 2
            $this->write($schema);
39
        }
40 2
        return $schema;
41
    }
42
43 3
    public function clear(): bool
44
    {
45 3
        $result = $this->cache->delete($this->key);
46 3
        if ($result === false) {
47 1
            throw new \RuntimeException("In the cache service was an error when deleting `{$this->key}` key.");
48
        }
49 2
        return true;
50
    }
51
52 2
    private function write(array $schema): bool
53
    {
54 2
        return $this->cache->set($this->key, $schema);
55
    }
56
}
57