1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Clubdeuce\Tessitura\Cache; |
4
|
|
|
|
5
|
|
|
use Clubdeuce\Tessitura\Interfaces\CacheInterface; |
6
|
|
|
|
7
|
|
|
class ArrayCache implements CacheInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Cached values |
11
|
|
|
* |
12
|
|
|
* @var mixed[] |
13
|
|
|
*/ |
14
|
|
|
private array $cache = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Expiration times for cached values |
18
|
|
|
* |
19
|
|
|
* @var int[] |
20
|
|
|
*/ |
21
|
|
|
private array $expiration = []; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Get a value from the cache. |
25
|
|
|
* |
26
|
|
|
* @param string $key The cache key |
27
|
|
|
* @return mixed|null The cached value or null if not found |
28
|
|
|
*/ |
29
|
7 |
|
public function get(string $key): mixed |
30
|
|
|
{ |
31
|
7 |
|
if (!$this->has($key)) { |
32
|
6 |
|
return null; |
33
|
|
|
} |
34
|
|
|
|
35
|
4 |
|
return $this->cache[$key]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Set a value in the cache. |
40
|
|
|
* |
41
|
|
|
* @param string $key The cache key |
42
|
|
|
* @param mixed $value The value to cache |
43
|
|
|
* @param int $ttl Time to live in seconds |
44
|
|
|
* @return bool True on success, false on failure |
45
|
|
|
*/ |
46
|
8 |
|
public function set(string $key, mixed $value, int $ttl = 3600): bool |
47
|
|
|
{ |
48
|
8 |
|
$this->cache[$key] = $value; |
49
|
8 |
|
if ($ttl > 0) { |
50
|
8 |
|
$this->expiration[$key] = time() + $ttl; |
51
|
|
|
} |
52
|
|
|
|
53
|
8 |
|
return true; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Check if a key exists in the cache. |
58
|
|
|
* |
59
|
|
|
* @param string $key The cache key |
60
|
|
|
* @return bool True if the key exists, false otherwise |
61
|
|
|
*/ |
62
|
9 |
|
public function has(string $key): bool |
63
|
|
|
{ |
64
|
9 |
|
if (!array_key_exists($key, $this->cache)) { |
65
|
6 |
|
return false; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
// Check if expired |
69
|
6 |
|
if (isset($this->expiration[$key]) && $this->expiration[$key] < time()) { |
70
|
2 |
|
unset($this->cache[$key], $this->expiration[$key]); |
71
|
|
|
|
72
|
2 |
|
return false; |
73
|
|
|
} |
74
|
|
|
|
75
|
5 |
|
return true; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Delete a value from the cache. |
80
|
|
|
* |
81
|
|
|
* @param string $key The cache key |
82
|
|
|
* @return bool True on success, false on failure |
83
|
|
|
*/ |
84
|
2 |
|
public function delete(string $key): bool |
85
|
|
|
{ |
86
|
2 |
|
unset($this->cache[$key], $this->expiration[$key]); |
87
|
|
|
|
88
|
2 |
|
return true; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* Clear all cached values. |
93
|
|
|
* |
94
|
|
|
* @return bool True on success, false on failure |
95
|
|
|
*/ |
96
|
1 |
|
public function clear(): bool |
97
|
|
|
{ |
98
|
1 |
|
$this->cache = []; |
99
|
1 |
|
$this->expiration = []; |
100
|
|
|
|
101
|
1 |
|
return true; |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|