-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayCache.php
More file actions
99 lines (82 loc) · 2.28 KB
/
Copy pathArrayCache.php
File metadata and controls
99 lines (82 loc) · 2.28 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
<?php
declare(strict_types=1);
namespace PivotPHP\ReactPHP\Security;
/**
* Example implementation of CacheInterface using an array for storage
*
* This is a proper implementation that can be effectively monitored and cleaned
* by MemoryGuard, unlike plain arrays.
*/
final class ArrayCache implements CacheInterface
{
private array $data = [];
private int $hits = 0;
private int $misses = 0;
public function get(string $key): mixed
{
if (array_key_exists($key, $this->data)) {
$this->hits++;
return $this->data[$key];
}
$this->misses++;
return null;
}
public function set(string $key, mixed $value): void
{
$this->data[$key] = $value;
}
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
public function delete(string $key): bool
{
if (array_key_exists($key, $this->data)) {
unset($this->data[$key]);
return true;
}
return false;
}
public function getMemorySize(): int
{
try {
return strlen(serialize($this->data));
} catch (\Throwable) {
return 0;
}
}
public function clean(int $targetSize): void
{
$currentSize = $this->getMemorySize();
if ($currentSize <= $targetSize) {
return;
}
// Remove oldest entries (assuming insertion order)
$removeCount = (int) (count($this->data) * 0.25); // Remove 25%
if ($removeCount > 0) {
$keys = array_keys($this->data);
for ($i = 0; $i < $removeCount; $i++) {
if (isset($keys[$i])) {
unset($this->data[$keys[$i]]);
}
}
}
}
public function clear(): void
{
$this->data = [];
}
public function getStats(): array
{
$total = $this->hits + $this->misses;
$hitRate = $total > 0 ? ($this->hits / $total) : 0.0;
return [
'size' => $this->getMemorySize(),
'count' => count($this->data),
'hit_rate' => $hitRate,
'memory_usage' => $this->getMemorySize(),
'hits' => $this->hits,
'misses' => $this->misses,
];
}
}