Chain::multiSave()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\PHPCacheAdapter\SimpleCache;
6
7
use Psr\SimpleCache;
8
9
final class Chain extends AbstractAdapter
10
{
11
    /**
12
     * @var \Psr\SimpleCache\CacheInterface[]
13
     */
14
    private $adapters;
15
16
    private function __construct(SimpleCache\CacheInterface ...$adapters)
17
    {
18
        $this->adapters = $adapters;
19
    }
20
21
    public static function create(SimpleCache\CacheInterface ...$adapters): self
22
    {
23
        return new self(...$adapters);
24
    }
25
26
    public function addAdapter(SimpleCache\CacheInterface $adapter): self
27
    {
28
        $this->adapters[] = $adapter;
29
        return $this;
30
    }
31
32
    public function flush(): bool
33
    {
34
        foreach ($this->adapters as $adapter) {
35
            $adapter->clear();
36
        }
37
38
        return true;
39
    }
40
41
    /**
42
     * @inheritDoc
43
     */
44
    protected function multiGet(array $keys, $default = null): \Generator
45
    {
46
        $results = [];
47
        foreach ($this->adapters as $adapter) {
48
            $results = iterator_to_array($adapter->getMultiple($keys, $default));
49
            if (array_filter($results, fn($val) => $val == $default) === []) {
50
                break;
51
            }
52
        }
53
54
        foreach ($results as $key => $result) {
55
            yield $key => $result;
56
        }
57
    }
58
59
    protected function multiSave(array $values, int $ttl = null): bool
60
    {
61
        $statuses = [];
62
        foreach ($this->adapters as $adapter) {
63
            $statuses[] = $adapter->setMultiple($values, $ttl);
64
        }
65
66
        return !in_array(false, $statuses);
67
    }
68
69
    protected function multiDelete(array $keys): bool
70
    {
71
        foreach ($this->adapters as $adapter) {
72
            $adapter->deleteMultiple($keys);
73
        }
74
75
        return true;
76
    }
77
78
    protected function exists(string $key): bool
79
    {
80
        foreach ($this->adapters as $adapter) {
81
            if ($adapter->has($key)) {
82
                return true;
83
            }
84
        }
85
86
        return false;
87
    }
88
}
89