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

RedisStore   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 85
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A delete() 0 7 2
A keys() 0 3 1
A get() 0 16 4
A set() 0 13 2
A getRedis() 0 3 1
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