| 1 | <?php |
||
| 10 | final class RedisRateLimiter implements RateLimiter |
||
| 11 | { |
||
| 12 | /** @var Redis */ |
||
| 13 | private $redis; |
||
| 14 | |||
| 15 | /** @var string */ |
||
| 16 | private $keyPrefix; |
||
| 17 | |||
| 18 | 3 | public function __construct(Redis $redis, string $keyPrefix = '') |
|
| 19 | { |
||
| 20 | 3 | $this->redis = $redis; |
|
| 21 | 3 | $this->keyPrefix = $keyPrefix; |
|
| 22 | 3 | } |
|
| 23 | |||
| 24 | 3 | public function handle(string $identifier, QuotaPolicy $quotaPolicy): Status |
|
| 25 | { |
||
| 26 | 3 | $key = $this->key($identifier, $quotaPolicy->getInterval()); |
|
| 27 | |||
| 28 | 3 | $current = (int) $this->redis->get($key); |
|
| 29 | |||
| 30 | 3 | if ($current <= $quotaPolicy->getQuota()) { |
|
| 31 | 3 | $current = $this->redis->incr($key); |
|
| 32 | |||
| 33 | 3 | if ($current === 1) { |
|
| 34 | 3 | $this->redis->expire($key, $quotaPolicy->getInterval()); |
|
| 35 | } |
||
| 36 | } |
||
| 37 | |||
| 38 | 3 | return Status::from( |
|
| 39 | 3 | $identifier, |
|
| 40 | 3 | $current, |
|
| 41 | 3 | $quotaPolicy, |
|
| 42 | 3 | (new DateTimeImmutable())->modify('+' . $this->ttl($key) . ' seconds') |
|
| 43 | ); |
||
| 44 | } |
||
| 45 | |||
| 46 | 3 | private function key(string $identifier, int $interval): string |
|
| 50 | |||
| 51 | 3 | private function ttl(string $key): int |
|
| 52 | { |
||
| 55 | } |
||
| 56 |