Redis::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
use RemotelyLiving\PHPCacheAdapter\Assertions;
9
10
final class Redis extends AbstractAdapter
11
{
12
    private \Redis $redis;
13
14
    private function __construct(\Redis $redis)
15
    {
16
        Assertions::assertExtensionLoaded('redis');
17
        $this->redis = $redis;
18
    }
19
20
    public static function create(\Redis $redis): SimpleCache\CacheInterface
21
    {
22
        return new self($redis);
23
    }
24
25
    public function flush(): bool
26
    {
27
        return $this->redis->flushAll();
28
    }
29
30
    /**
31
     * @inheritDoc
32
     */
33
    protected function multiGet(array $keys, $default = null): \Generator
34
    {
35
        $values = $this->redis->mget($keys);
36
        foreach ($keys as $index => $key) {
37
            yield $key => ($values[$index] !== false) ? \unserialize($values[$index]) : $default;
38
        }
39
    }
40
41
    protected function multiSave(array $values, int $ttl = null): bool
42
    {
43
        $multi = $this->redis->multi(\Redis::PIPELINE);
44
        foreach ($values as $key => $value) {
45
            $multi->set($key, \serialize($value), $ttl ?? $this->getDefaultTTLSeconds());
46
        }
47
48
        return !empty($this->redis->exec());
49
    }
50
51
    protected function multiDelete(array $keys): bool
52
    {
53
        return $this->redis->del($keys) === count($keys);
54
    }
55
56
    protected function exists(string $key): bool
57
    {
58
        return (bool) $this->redis->exists($key);
59
    }
60
}
61