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
|
|
|
*/ |
21
|
1 |
|
public function __construct(array $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
|
6 |
|
public function get(string $key, bool $withExpired = false) |
40
|
|
|
{ |
41
|
6 |
|
if (false === strpos($key, self::TUS_REDIS_PREFIX)) { |
42
|
6 |
|
$key = self::TUS_REDIS_PREFIX . $key; |
43
|
|
|
} |
44
|
|
|
|
45
|
6 |
|
$contents = $this->redis->get($key); |
46
|
6 |
|
$contents = json_decode($contents, true); |
47
|
|
|
|
48
|
6 |
|
if ($withExpired) { |
49
|
1 |
|
return $contents; |
50
|
|
|
} |
51
|
|
|
|
52
|
6 |
|
$isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now()); |
53
|
|
|
|
54
|
6 |
|
return $isExpired ? null : $contents; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritDoc} |
59
|
|
|
*/ |
60
|
3 |
|
public function set(string $key, $value) |
61
|
|
|
{ |
62
|
3 |
|
$contents = $this->get($key) ?? []; |
63
|
|
|
|
64
|
3 |
|
if (is_array($value)) { |
65
|
3 |
|
$contents = $value + $contents; |
66
|
|
|
} else { |
67
|
1 |
|
array_push($contents, $value); |
68
|
|
|
} |
69
|
|
|
|
70
|
3 |
|
$status = $this->redis->set(self::TUS_REDIS_PREFIX . $key, json_encode($contents)); |
71
|
|
|
|
72
|
3 |
|
return 'OK' === $status->getPayload(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* {@inheritDoc} |
77
|
|
|
*/ |
78
|
2 |
|
public function delete(string $key) |
79
|
|
|
{ |
80
|
2 |
|
if (false === strpos($key, self::TUS_REDIS_PREFIX)) { |
81
|
2 |
|
$key = self::TUS_REDIS_PREFIX . $key; |
82
|
|
|
} |
83
|
|
|
|
84
|
2 |
|
return $this->redis->del($key) > 0; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* {@inheritDoc} |
89
|
|
|
*/ |
90
|
1 |
|
public function keys() : array |
91
|
|
|
{ |
92
|
1 |
|
return $this->redis->keys(self::TUS_REDIS_PREFIX . '*'); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|