1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Koded package. |
4
|
|
|
* |
5
|
|
|
* (c) Mihail Binev <[email protected]> |
6
|
|
|
* |
7
|
|
|
* Please view the LICENSE distributed with this source code |
8
|
|
|
* for the full copyright and license information. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Koded\Caching\Client; |
12
|
|
|
|
13
|
|
|
use Koded\Caching\Cache; |
14
|
|
|
use function array_key_exists; |
15
|
|
|
use function Koded\Caching\verify_key; |
16
|
|
|
use function Koded\Stdlib\now; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @property MemoryClient client |
20
|
|
|
*/ |
21
|
|
|
final class MemoryClient implements Cache |
22
|
|
|
{ |
23
|
|
|
use ClientTrait, MultiplesTrait; |
24
|
|
|
|
25
|
|
|
private array $storage = []; |
26
|
|
|
private array $expiration = []; |
27
|
|
|
|
28
|
75 |
|
public function __construct(int $ttl = null) |
29
|
|
|
{ |
30
|
75 |
|
$this->ttl = $ttl; |
31
|
|
|
} |
32
|
|
|
|
33
|
46 |
|
public function get(string $key, mixed $default = null): mixed |
34
|
|
|
{ |
35
|
46 |
|
return $this->has($key) ? $this->storage[$key] : $default; |
36
|
|
|
} |
37
|
|
|
|
38
|
50 |
|
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool |
39
|
|
|
{ |
40
|
50 |
|
verify_key($key); |
41
|
50 |
|
if (1 > $expiration = $this->timestampWithGlobalTtl($ttl, Cache::DATE_FAR_FAR_AWAY)) { |
42
|
2 |
|
unset($this->storage[$key], $this->expiration[$key]); |
43
|
|
|
} else { |
44
|
|
|
// Loose the reference to the object |
45
|
49 |
|
$this->storage[$key] = \is_object($value) ? clone $value : $value; |
46
|
49 |
|
$this->expiration[$key] = $expiration; |
47
|
|
|
} |
48
|
50 |
|
return true; |
49
|
|
|
} |
50
|
|
|
|
51
|
8 |
|
public function delete(string $key): bool |
52
|
|
|
{ |
53
|
8 |
|
if (false === $this->has($key)) { |
54
|
6 |
|
return true; |
55
|
|
|
} |
56
|
6 |
|
unset($this->storage[$key], $this->expiration[$key]); |
57
|
6 |
|
return true; |
58
|
|
|
} |
59
|
|
|
|
60
|
71 |
|
public function clear(): bool |
61
|
|
|
{ |
62
|
71 |
|
$this->storage = []; |
63
|
71 |
|
$this->expiration = []; |
64
|
71 |
|
return true; |
65
|
|
|
} |
66
|
|
|
|
67
|
51 |
|
public function has(string $key): bool |
68
|
|
|
{ |
69
|
51 |
|
verify_key($key); |
70
|
51 |
|
if (false === array_key_exists($key, $this->expiration)) { |
71
|
17 |
|
return false; |
72
|
|
|
} |
73
|
45 |
|
if ($this->expiration[$key] <= now()->getTimestamp()) { |
74
|
2 |
|
unset($this->storage[$key], $this->expiration[$key]); |
75
|
2 |
|
return false; |
76
|
|
|
} |
77
|
45 |
|
return true; |
78
|
|
|
} |
79
|
|
|
|
80
|
2 |
|
public function getExpirationFor(string $key): ?int |
81
|
|
|
{ |
82
|
2 |
|
return $this->expiration[$key] ?? null; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|