1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace RateLimit; |
6
|
|
|
|
7
|
|
|
use RateLimit\Exception\LimitExceeded; |
8
|
|
|
|
9
|
|
|
final class ArrayRateLimiter implements RateLimiter, SilentRateLimiter |
10
|
|
|
{ |
11
|
|
|
/** @var array */ |
12
|
|
|
private $cache = []; |
13
|
|
|
|
14
|
|
View Code Duplication |
public function limit(string $identifier, Rate $rate): void |
|
|
|
|
15
|
|
|
{ |
16
|
|
|
$key = $this->key($identifier, $rate->getInterval()); |
17
|
|
|
|
18
|
|
|
$current = $this->getCurrent($key); |
19
|
|
|
|
20
|
|
|
if ($current >= $rate->getOperations()) { |
21
|
|
|
throw LimitExceeded::for($identifier, $rate); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
$this->updateCounter($key, $rate->getInterval()); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
View Code Duplication |
public function limitSilently(string $identifier, Rate $rate): Status |
|
|
|
|
28
|
|
|
{ |
29
|
|
|
$key = $this->key($identifier, $rate->getInterval()); |
30
|
|
|
|
31
|
|
|
$current = $this->getCurrent($key); |
32
|
|
|
|
33
|
|
|
if ($current <= $rate->getOperations()) { |
34
|
|
|
$current = $this->updateCounter($key, $rate->getInterval()); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return Status::from( |
38
|
|
|
$identifier, |
39
|
|
|
$current, |
40
|
|
|
$rate->getOperations(), |
41
|
|
|
time() + $this->ttl($key) |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function key(string $identifier, int $interval): string |
46
|
|
|
{ |
47
|
|
|
return "{$identifier}:$interval"; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function getCurrent(string $key): int |
51
|
|
|
{ |
52
|
|
|
if (isset($this->cache[$key])) { |
53
|
|
|
$this->cache[$key] = array_filter($this->cache[$key], function (int $ttl) { |
54
|
|
|
return $ttl > time(); |
55
|
|
|
}); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return isset($this->cache[$key]) ? count($this->cache[$key]) : 0; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function updateCounter(string $key, int $interval): int |
62
|
|
|
{ |
63
|
|
|
if (!isset($this->cache[$key])) { |
64
|
|
|
$this->cache[$key] = []; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
array_push($this->cache[$key], time() + $interval); |
68
|
|
|
$current = count($this->cache[$key]); |
69
|
|
|
|
70
|
|
|
return $current; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function ttl(string $key): int |
74
|
|
|
{ |
75
|
|
|
return max($this->cache[$key] ?? 0); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.