1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace PTS\RateLimiter\Adapter; |
5
|
|
|
|
6
|
|
|
use PTS\RateLimiter\StoreInterface; |
7
|
|
|
|
8
|
|
|
class MemoryAdapter implements StoreInterface |
9
|
|
|
{ |
10
|
|
|
protected int $cleanExpired = 30; |
|
|
|
|
11
|
|
|
protected int $lastClean = 0; |
12
|
|
|
|
13
|
|
|
protected array $store = []; |
14
|
|
|
protected array $ttlKeys = []; |
15
|
|
|
|
16
|
16 |
|
public function get(string $key): int |
17
|
|
|
{ |
18
|
16 |
|
$this->isNeedCleanExpired() && $this->cleanExpired(); |
19
|
16 |
|
return $this->store[$key] ?? 0; |
20
|
|
|
} |
21
|
|
|
|
22
|
16 |
|
public function __construct(int $cleanExpired = 30) |
23
|
|
|
{ |
24
|
16 |
|
$this->cleanExpired = $cleanExpired; |
25
|
16 |
|
$this->lastClean = time(); |
26
|
16 |
|
} |
27
|
|
|
|
28
|
14 |
|
public function inc(string $key, int $ttl = 60): int |
29
|
|
|
{ |
30
|
14 |
|
$value = $this->get($key); |
31
|
14 |
|
$this->store[$key] = ++$value; |
32
|
|
|
|
33
|
14 |
|
if ($value === 1) { |
34
|
14 |
|
$this->ttlKeys[$key] = time() + $ttl; |
35
|
|
|
} |
36
|
|
|
|
37
|
14 |
|
return $value; |
38
|
|
|
} |
39
|
|
|
|
40
|
12 |
|
public function reset(string $key): bool |
41
|
|
|
{ |
42
|
12 |
|
unset($this->store[$key], $this->ttlKeys[$key]); |
43
|
12 |
|
return true; |
44
|
|
|
} |
45
|
|
|
|
46
|
6 |
|
public function isExceeded(string $key, int $max): bool |
47
|
|
|
{ |
48
|
6 |
|
$value = $this->get($key); |
49
|
6 |
|
return $value >= $max; |
50
|
|
|
} |
51
|
|
|
|
52
|
16 |
|
protected function isNeedCleanExpired(): bool |
53
|
|
|
{ |
54
|
16 |
|
return ($this->lastClean + $this->cleanExpired) <= time(); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
protected function cleanExpired(): void |
58
|
|
|
{ |
59
|
1 |
|
$current = time(); |
60
|
|
|
|
61
|
|
|
$this->ttlKeys = array_filter ($this->ttlKeys, function (int $time, string $key) use ($current) { |
62
|
1 |
|
$isExpired = $time < $current; |
63
|
1 |
|
if ($isExpired) { |
64
|
1 |
|
unset($this->store[$key]); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
return !$isExpired; |
68
|
1 |
|
}, ARRAY_FILTER_USE_BOTH); |
69
|
1 |
|
} |
70
|
|
|
|
71
|
2 |
|
public function ttl(string $key): ?int |
72
|
|
|
{ |
73
|
2 |
|
if (array_key_exists($key, $this->ttlKeys)) { |
74
|
2 |
|
$ttl = $this->ttlKeys[$key] - time(); |
75
|
2 |
|
return $ttl > 0 ? $ttl : 0; |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
return null; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|