1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace RateLimit; |
6
|
|
|
|
7
|
|
|
use RateLimit\Exception\LimitExceeded; |
8
|
|
|
|
9
|
|
|
abstract class AbstractTTLRateLimiter implements RateLimiter, SilentRateLimiter |
10
|
|
|
{ |
11
|
|
|
/** @var string */ |
12
|
|
|
private $keyPrefix; |
13
|
|
|
|
14
|
10 |
|
public function __construct(string $keyPrefix = '') |
15
|
|
|
{ |
16
|
10 |
|
$this->keyPrefix = $keyPrefix; |
17
|
10 |
|
} |
18
|
|
|
|
19
|
4 |
|
final public function limit(string $identifier, Rate $rate): void |
20
|
|
|
{ |
21
|
4 |
|
$key = $this->key($identifier, $rate->getInterval()); |
22
|
|
|
|
23
|
4 |
|
$current = $this->getCurrent($key); |
24
|
4 |
|
if ($current >= $rate->getOperations()) { |
25
|
4 |
|
throw LimitExceeded::for($identifier, $rate); |
26
|
|
|
} |
27
|
|
|
|
28
|
4 |
|
$this->updateCounter($key, $rate->getInterval()); |
29
|
4 |
|
} |
30
|
|
|
|
31
|
6 |
|
final public function limitSilently(string $identifier, Rate $rate): Status |
32
|
|
|
{ |
33
|
6 |
|
$key = $this->key($identifier, $rate->getInterval()); |
34
|
|
|
|
35
|
6 |
|
$current = $this->getCurrent($key); |
36
|
6 |
|
if ($current <= $rate->getOperations()) { |
37
|
6 |
|
$current = $this->updateCounter($key, $rate->getInterval()); |
38
|
|
|
} |
39
|
|
|
|
40
|
6 |
|
return Status::from( |
41
|
6 |
|
$identifier, |
42
|
6 |
|
$current, |
43
|
6 |
|
$rate->getOperations(), |
44
|
6 |
|
time() + $this->ttl($key) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
10 |
|
private function key(string $identifier, int $interval): string |
49
|
|
|
{ |
50
|
10 |
|
return \sprintf('%s%s:%d', $this->keyPrefix, $identifier, $interval); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
abstract protected function getCurrent(string $key): int; |
54
|
|
|
|
55
|
|
|
abstract protected function updateCounter(string $key, int $interval): int; |
56
|
|
|
|
57
|
|
|
abstract protected function ttl(string $key): int; |
58
|
|
|
} |
59
|
|
|
|