-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathCache.php
More file actions
285 lines (236 loc) · 6.97 KB
/
Cache.php
File metadata and controls
285 lines (236 loc) · 6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
declare(strict_types=1);
namespace Detection\Cache;
use Psr\SimpleCache\CacheInterface;
use DateInterval;
use DateTime;
use function is_int;
use function is_iterable;
use function is_string;
use function time;
/**
* In-memory cache implementation of PSR-16.
*
* @see https://www.php-fig.org/psr/psr-16/
*
* Public method parameters are intentionally left without scalar type
* declarations (return types are kept). This keeps the class
* Liskov-compatible with PSR-16 v1/v2 as well as v3, so it loads cleanly
* in hosts (e.g. WordPress sites) where another plugin's autoloader has
* already registered an older `Psr\SimpleCache\CacheInterface`.
* Re-narrowing these parameters will break that compatibility. See
* https://github.com/serbanghita/Mobile-Detect/issues/989.
*/
class Cache implements CacheInterface
{
protected array $cache = [];
/**
* @param string $key
* @param mixed $default
* @return mixed
* @throws CacheInvalidArgumentException
*/
public function get($key, mixed $default = null): mixed
{
$key = $this->checkKey($key);
if (isset($this->cache[$key])) {
if ($this->cache[$key]['ttl'] === null || $this->cache[$key]['ttl'] > time()) {
return $this->cache[$key]['content'];
}
$this->deleteSingle($key);
}
return $default;
}
/**
* @param string $key
* @param mixed $value
* @param int|DateInterval|null $ttl
* @throws CacheInvalidArgumentException
*/
public function set($key, mixed $value, $ttl = null): bool
{
$key = $this->checkKey($key);
$ttl = $this->checkTtl($ttl);
// From https://www.php-fig.org/psr/psr-16/ "Definitions" -> "Expiration"
// If a negative or zero TTL is provided, the item MUST be deleted from the cache if it exists, as it is expired already.
if (is_int($ttl) && $ttl <= 0) {
$this->deleteSingle($key);
return false;
}
$ttl = $this->getTTL($ttl);
if ($ttl !== null) {
$ttl = (time() + $ttl);
}
$this->cache[$key] = ['ttl' => $ttl, 'content' => $value];
return true;
}
/**
* @param string $key
* @throws CacheInvalidArgumentException
*/
public function delete($key): bool
{
$key = $this->checkKey($key);
$this->deleteSingle($key);
return true;
}
/**
* Deletes the cache item from memory.
*/
private function deleteSingle(string $key): void
{
unset($this->cache[$key]);
}
/** @inheritdoc */
public function clear(): bool
{
$this->cache = [];
return true;
}
/**
* @param string $key
* @throws CacheInvalidArgumentException
*/
public function has($key): bool
{
$key = $this->checkKey($key);
if (isset($this->cache[$key])) {
if ($this->cache[$key]['ttl'] === null || $this->cache[$key]['ttl'] > time()) {
return true;
}
$this->deleteSingle($key);
}
return false;
}
/**
* @param iterable<string> $keys
* @param mixed $default
* @throws CacheInvalidArgumentException
*/
public function getMultiple($keys, mixed $default = null): iterable
{
$keys = $this->checkIterable($keys, 'keys');
$data = [];
foreach ($keys as $key) {
$data[$key] = $this->get($key, $default);
}
return $data;
}
/**
* @param iterable<string, mixed> $values
* @param int|DateInterval|null $ttl
* @throws CacheInvalidArgumentException
*/
public function setMultiple($values, $ttl = null): bool
{
$values = $this->checkIterable($values, 'values');
$ttl = $this->checkTtl($ttl);
$return = [];
foreach ($values as $key => $value) {
$return[] = $this->set($key, $value, $ttl);
}
return $this->checkReturn($return);
}
/**
* @param iterable<string> $keys
* @throws CacheInvalidArgumentException
*/
public function deleteMultiple($keys): bool
{
$keys = $this->checkIterable($keys, 'keys');
foreach ($keys as $key) {
$this->delete($key);
}
return true;
}
/**
* @param mixed $key
* @throws CacheInvalidArgumentException
*/
protected function checkKey($key): string
{
if (!is_string($key)) {
throw new CacheInvalidArgumentException('Cache key must be a string.');
}
if ($key === '' || !preg_match('/^[A-Za-z0-9_.]{1,64}$/', $key)) {
throw new CacheInvalidArgumentException("Invalid key: '$key'. Must be alphanumeric, can contain _ and . and can be maximum of 64 chars.");
}
return $key;
}
/**
* @param mixed $ttl
* @throws CacheInvalidArgumentException
*/
protected function checkTtl($ttl): int|DateInterval|null
{
if ($ttl !== null && !is_int($ttl) && !($ttl instanceof DateInterval)) {
throw new CacheInvalidArgumentException('TTL must be null, int, or DateInterval.');
}
return $ttl;
}
/**
* @param mixed $iterable
* @return iterable<mixed>
* @throws CacheInvalidArgumentException
*/
protected function checkIterable($iterable, string $argName): iterable
{
if (!is_iterable($iterable)) {
throw new CacheInvalidArgumentException(sprintf('%s must be iterable.', ucfirst($argName)));
}
return $iterable;
}
protected function getTTL(DateInterval|int|null $ttl): ?int
{
if ($ttl instanceof DateInterval) {
return (new DateTime())->add($ttl)->getTimestamp() - time();
}
// We treat 0 as a valid value.
if (is_int($ttl)) {
return $ttl;
}
return null;
}
/**
* @param bool[]|int[] $booleans
*/
protected function checkReturn(array $booleans): bool
{
foreach ($booleans as $boolean) {
if (!$boolean) {
return false;
}
}
return true;
}
/**
* Get all cache keys.
*
* @internal Needed for testing purposes.
* @return array{string}
*/
public function getKeys(): array
{
return array_keys($this->cache);
}
/**
* Evict all expired items from the cache.
*
* Useful for long-running processes (CLI scripts, workers, daemons)
* to periodically clean up expired entries and free memory.
*
* @return int Number of items evicted
*/
public function evictExpired(): int
{
$evicted = 0;
$now = time();
foreach ($this->cache as $key => $item) {
if ($item['ttl'] !== null && $item['ttl'] <= $now) {
unset($this->cache[$key]);
$evicted++;
}
}
return $evicted;
}
}