Passed
Pull Request — master (#68)
by Aleksei
04:14
created

SimpleCacheSchemaProvider   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 2
b 0
f 0
dl 0
loc 41
ccs 0
cts 18
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A withConfig() 0 5 1
A clear() 0 3 1
A write() 0 3 1
A read() 0 13 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
    public function __construct(CacheInterface $cache)
17
    {
18
        $this->cache = $cache;
19
    }
20
21
    public function withConfig(array $config): self
22
    {
23
        $new = clone $this;
24
        $new->key = $config['key'] ?? self::DEFAULT_KEY;
25
        return $new;
26
    }
27
28
    public function read(?SchemaProviderInterface $nextProvider = null): ?array
29
    {
30
        $schema = $this->cache->get($this->key);
31
32
        if ($schema !== null || $nextProvider === null) {
33
            return $schema;
34
        }
35
36
        $schema = $nextProvider->read();
37
        if ($schema !== null) {
38
            $this->write($schema);
39
        }
40
        return $schema;
41
    }
42
43
    public function clear(): bool
44
    {
45
        return $this->cache->delete($this->key);
46
    }
47
48
    private function write(array $schema): bool
49
    {
50
        return $this->cache->set($this->key, $schema);
51
    }
52
}
53