Passed
Pull Request — master (#4)
by Ankit
06:17 queued 43s
created

RedisStore::get()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

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