RedisStore::get()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 3
b 0
f 0
nc 8
nop 2
dl 0
loc 22
ccs 12
cts 12
cp 1
crap 5
rs 9.6111
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 2
    public function getRedis() : RedisClient
32
    {
33 2
        return $this->redis;
34
    }
35
36
    /**
37
     * {@inheritDoc}
38
     */
39 7
    public function get(string $key, bool $withExpired = false)
40
    {
41 7
        $prefix = $this->getPrefix();
42
43 7
        if (false === strpos($key, $prefix)) {
44 7
            $key = $prefix . $key;
45
        }
46
47 7
        $contents = $this->redis->get($key);
48 7
        $contents = json_decode($contents, true);
49
50 7
        if ($withExpired) {
51 1
            return $contents;
52
        }
53
54 7
        if ( ! $contents) {
55 3
            return null;
56
        }
57
58 6
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
59
60 6
        return $isExpired ? null : $contents;
61
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66 4
    public function set(string $key, $value)
67
    {
68 4
        $contents = $this->get($key) ?? [];
69
70 4
        if (\is_array($value)) {
71 4
            $contents = $value + $contents;
72
        } else {
73 1
            $contents[] = $value;
74
        }
75
76 4
        $status = $this->redis->set($this->getPrefix() . $key, json_encode($contents));
77
78 4
        return 'OK' === $status->getPayload();
79
    }
80
81
    /**
82
     * {@inheritDoc}
83
     */
84 2
    public function delete(string $key) : bool
85
    {
86 2
        $prefix = $this->getPrefix();
87
88 2
        if (false === strpos($key, $prefix)) {
89 2
            $key = $prefix . $key;
90
        }
91
92 2
        return $this->redis->del([$key]) > 0;
93
    }
94
95
    /**
96
     * {@inheritDoc}
97
     */
98 1
    public function keys() : array
99
    {
100 1
        return $this->redis->keys($this->getPrefix() . '*');
101
    }
102
}
103