|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Koded package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Mihail Binev <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* Please view the LICENSE distributed with this source code |
|
9
|
|
|
* for the full copyright and license information. |
|
10
|
|
|
* |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Koded\Caching\Client; |
|
14
|
|
|
|
|
15
|
|
|
use Koded\Caching\Cache; |
|
16
|
|
|
use Koded\Stdlib\Interfaces\Serializer; |
|
17
|
|
|
use Predis\Client; |
|
18
|
|
|
use function Koded\Caching\verify_key; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Class PredisClient uses the Predis library. |
|
22
|
|
|
* |
|
23
|
|
|
* @property Client client |
|
24
|
|
|
*/ |
|
25
|
|
|
final class PredisClient implements Cache |
|
26
|
|
|
{ |
|
27
|
|
|
use ClientTrait, MultiplesTrait; |
|
28
|
|
|
|
|
29
|
|
|
private $serializer; |
|
30
|
|
|
|
|
31
|
188 |
|
public function __construct(Client $client, Serializer $serializer, int $ttl = null) |
|
32
|
|
|
{ |
|
33
|
188 |
|
$this->client = $client; |
|
34
|
188 |
|
$this->serializer = $serializer; |
|
35
|
188 |
|
$this->ttl = $ttl; |
|
36
|
188 |
|
} |
|
37
|
|
|
|
|
38
|
|
|
|
|
39
|
61 |
|
public function get($key, $default = null) |
|
40
|
|
|
{ |
|
41
|
61 |
|
return $this->has($key) |
|
42
|
37 |
|
? $this->serializer->unserialize($this->client->get($key)) |
|
43
|
44 |
|
: $default; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
|
|
47
|
70 |
|
public function set($key, $value, $ttl = null) |
|
48
|
|
|
{ |
|
49
|
70 |
|
verify_key($key); |
|
50
|
53 |
|
$expiration = $this->secondsWithGlobalTtl($ttl); |
|
51
|
|
|
|
|
52
|
43 |
|
if (null === $ttl && 0 === $expiration) { |
|
53
|
41 |
|
return 'OK' === $this->client->set($key, $this->serializer->serialize($value))->getPayload(); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
3 |
|
if ($expiration > 0) { |
|
57
|
2 |
|
return 'OK' === $this->client->setex($key, $expiration, $this->serializer->serialize($value))->getPayload(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
1 |
|
$this->client->del($key); |
|
61
|
|
|
|
|
62
|
1 |
|
return true; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
|
|
66
|
22 |
|
public function delete($key) |
|
67
|
|
|
{ |
|
68
|
22 |
|
if (false === $this->has($key)) { |
|
69
|
4 |
|
return true; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
4 |
|
return 1 === $this->client->del($key); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
|
|
76
|
187 |
|
public function clear() |
|
77
|
|
|
{ |
|
78
|
187 |
|
return 'OK' === $this->client->flushdb()->getPayload(); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
|
|
82
|
96 |
|
public function has($key) |
|
83
|
|
|
{ |
|
84
|
96 |
|
verify_key($key); |
|
85
|
|
|
|
|
86
|
45 |
|
return 1 === $this->client->exists($key); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|