-
Notifications
You must be signed in to change notification settings - Fork 49
/
InMemoryRateLimiter.php
60 lines (46 loc) · 1.46 KB
/
InMemoryRateLimiter.php
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
<?php
declare(strict_types=1);
namespace RateLimit;
use RateLimit\Exception\LimitExceeded;
use function floor;
use function time;
final class InMemoryRateLimiter extends ConfigurableRateLimiter implements RateLimiter, SilentRateLimiter
{
private array $store = [];
public function limit(string $identifier): void
{
$key = $this->key($identifier);
$current = $this->hit($key);
if ($current > $this->rate->getOperations()) {
throw LimitExceeded::for($identifier, $this->rate);
}
}
public function limitSilently(string $identifier): Status
{
$key = $this->key($identifier);
$current = $this->hit($key);
return Status::from(
$identifier,
$current,
$this->rate->getOperations(),
$this->store[$key]['reset_time']
);
}
private function key(string $identifier): string
{
$interval = $this->rate->getInterval();
return "$identifier:$interval:" . floor(time() / $interval);
}
private function hit(string $key): int
{
if (!isset($this->store[$key])) {
$this->store[$key] = [
'current' => 1,
'reset_time' => time() + $this->rate->getInterval(),
];
} elseif ($this->store[$key]['current'] <= $this->rate->getOperations()) {
$this->store[$key]['current']++;
}
return $this->store[$key]['current'];
}
}