Passed
Pull Request — master (#213)
by Ankit
01:59
created

RedisStore::keys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace TusPhp\Cache;
4
5
use Carbon\Carbon;
6
use TusPhp\Config;
7
use Predis\Client as RedisClient;
8
9
class RedisStore extends AbstractCache
10
{
11
    /** @var RedisClient */
12
    protected $redis;
13
14
    /**
15
     * RedisStore constructor.
16
     *
17
     * @param array $options
18
     */
19 1
    public function __construct(array $options = [])
20
    {
21 1
        $options = empty($options) ? Config::get('redis') : $options;
22
23 1
        $this->redis = new RedisClient($options);
24 1
    }
25
26
    /**
27
     * Get redis.
28
     *
29
     * @return RedisClient
30
     */
31 1
    public function getRedis() : RedisClient
32
    {
33 1
        return $this->redis;
34
    }
35
36
    /**
37
     * {@inheritDoc}
38
     */
39
    public function get(string $key, bool $withExpired = false)
40
    {
41
        $prefix = $this->getPrefix();
42
43
        if (false === strpos($key, $prefix)) {
44
            $key = $prefix . $key;
45
        }
46
47
        $contents = $this->redis->get($key);
48
        $contents = json_decode($contents, true) ?? [];
49
50
        if ($withExpired) {
51
            return $contents;
52
        }
53
54
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
55
56
        return $isExpired ? null : $contents;
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62
    public function set(string $key, $value)
63
    {
64
        $contents = $this->get($key) ?? [];
65
66
        if (\is_array($value)) {
67
            $contents = $value + $contents;
68
        } else {
69
            $contents[] = $value;
70
        }
71
72
        $status = $this->redis->set($this->getPrefix() . $key, json_encode($contents));
73
74
        return 'OK' === $status->getPayload();
75
    }
76
77
    /**
78
     * {@inheritDoc}
79
     */
80
    public function delete(string $key) : bool
81
    {
82
        $prefix = $this->getPrefix();
83
84
        if (false === strpos($key, $prefix)) {
85
            $key = $prefix . $key;
86
        }
87
88
        return $this->redis->del([$key]) > 0;
89
    }
90
91
    /**
92
     * {@inheritDoc}
93
     */
94
    public function keys() : array
95
    {
96
        return $this->redis->keys($this->getPrefix() . '*');
97
    }
98
}
99