1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jlaswell\SimpleCache; |
4
|
|
|
|
5
|
|
|
use Traversable; |
6
|
|
|
use Psr\SimpleCache\CacheInterface; |
7
|
|
|
use Jlaswell\SimpleCache\KeyValidation; |
8
|
|
|
|
9
|
|
|
class ArrayCache implements CacheInterface |
10
|
|
|
{ |
11
|
|
|
use KeyValidation; |
12
|
|
|
|
13
|
|
|
protected $data = []; |
14
|
|
|
|
15
|
|
|
public function __construct(array $data = []) |
16
|
|
|
{ |
17
|
|
|
$this->data = array_combine( |
18
|
|
|
$this->transformKeys(array_keys($data)), |
19
|
|
|
array_values($data) |
20
|
|
|
); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function get($key, $default = null) |
24
|
|
|
{ |
25
|
|
|
$this->validateKey($key); |
26
|
|
|
|
27
|
|
|
return $this->data[$key] ?? $default; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function set($key, $value, $ttl = null) |
31
|
|
|
{ |
32
|
|
|
$this->validateKey($key); |
33
|
|
|
$this->data[$key] = $value; |
34
|
|
|
|
35
|
|
|
return true; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function delete($key) |
39
|
|
|
{ |
40
|
|
|
$this->validateKey($key); |
41
|
|
|
unset($this->data[$key]); |
42
|
|
|
|
43
|
|
|
return true; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function clear() |
47
|
|
|
{ |
48
|
|
|
$this->data = []; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function getMultiple($keys, $default = null) |
52
|
|
|
{ |
53
|
|
|
$keys = $this->transformKeys($keys); |
54
|
|
|
|
55
|
|
|
$data = array_merge( |
56
|
|
|
array_fill_keys($keys, $default), |
57
|
|
|
array_intersect_key($this->data, array_flip($keys)) |
58
|
|
|
); |
59
|
|
|
|
60
|
|
|
return $data; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function setMultiple($items, $ttl = null) |
64
|
|
|
{ |
65
|
|
|
$this->transformKeys($items); |
66
|
|
|
foreach ($items as $key => $value) { |
67
|
|
|
$this->data[$key] = $value; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return true; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function deleteMultiple($keys) |
74
|
|
|
{ |
75
|
|
|
$keys = $this->transformKeys($keys); |
76
|
|
|
$this->data = array_diff_key($this->data, array_flip($keys)); |
77
|
|
|
|
78
|
|
|
return true; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function has($key) |
82
|
|
|
{ |
83
|
|
|
$this->validateKey($key); |
84
|
|
|
|
85
|
|
|
return isset($this->data[$key]); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|