1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jlaswell\SimpleCache; |
4
|
|
|
|
5
|
|
|
use Traversable; |
6
|
|
|
use Predis\Client; |
7
|
|
|
use Psr\SimpleCache\CacheInterface; |
8
|
|
|
use Jlaswell\SimpleCache\KeyValidation; |
9
|
|
|
|
10
|
|
|
class PredisCache implements CacheInterface |
11
|
|
|
{ |
12
|
|
|
use KeyValidation; |
13
|
|
|
|
14
|
|
|
private $client; |
15
|
|
|
|
16
|
|
|
public function __construct(Client $client, $data = null) |
17
|
|
|
{ |
18
|
|
|
$this->client = $client; |
19
|
|
|
if (!is_null($data)) { |
20
|
|
|
foreach ($data as $key => $value) { |
21
|
|
|
$this->set($key, $value); |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function get($key, $default = null) |
27
|
|
|
{ |
28
|
|
|
return $this->client->get($this->validateKey($key)) ?? $default; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function set($key, $value, $ttl = null) |
32
|
|
|
{ |
33
|
|
|
return $this->client->set($this->validateKey($key), $value) |
34
|
|
|
->getPayload() === 'OK'; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function delete($key) |
38
|
|
|
{ |
39
|
|
|
$removedKeys = $this->client->del($this->validateKey($key)); |
40
|
|
|
|
41
|
|
|
return $removedKeys === 1 || $removedKeys === 0; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function clear() |
45
|
|
|
{ |
46
|
|
|
$this->client->flushall(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getMultiple($keys, $default = null) |
50
|
|
|
{ |
51
|
|
|
$keys = $this->transformKeys($keys); |
52
|
|
|
$values = $this->client->mget($keys); |
53
|
|
|
|
54
|
|
|
if (!is_null($default)) { |
55
|
|
|
foreach ($values as $key => $value) { |
56
|
|
|
is_null($value) ? $values[$key] = $default : null; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return array_combine($keys, $values); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function setMultiple($items, $ttl = null) |
64
|
|
|
{ |
65
|
|
|
$this->transformKeys($items); |
66
|
|
|
if ($items instanceof Traversable) { |
67
|
|
|
$items = iterator_to_array($items, true); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $this->client->mset($items)->getPayload() === 'OK'; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function deleteMultiple($keys) |
74
|
|
|
{ |
75
|
|
|
return $this->client->del($this->transformKeys($keys)) <= sizeof($keys); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function has($key) |
79
|
|
|
{ |
80
|
|
|
return !is_null($this->client->get($this->validateKey($key))); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|