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