Completed
Push — master ( f8807b...5769db )
by Nikola
06:22
created

RedisRateLimiter::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
rs 9.584
ccs 9
cts 9
cp 1
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use DateTimeImmutable;
8
use Redis;
9
10
final class RedisRateLimiter implements RateLimiter
11
{
12
    /** @var Redis */
13
    private $redis;
14
15
    /** @var string */
16
    private $keyPrefix;
17
18
    public function __construct(Redis $redis, string $keyPrefix = '')
19
    {
20
        $this->redis = $redis;
21
        $this->keyPrefix = $keyPrefix;
22
    }
23
24
    public function handle(string $identifier, QuotaPolicy $quotaPolicy): Status
25
    {
26
        $key = $this->key($identifier, $quotaPolicy->getInterval());
27 9
28
        $current = (int) $this->redis->get($key);
29 9
30
        if ($current <= $quotaPolicy->getQuota()) {
31 9
            $this->redis->incr($key);
32 9
33
            if ($current === 1) {
34 4
                $this->redis->expire($key, $quotaPolicy->getInterval());
35
            }
36 4
        }
37
38 4
        return Status::from(
39 4
            $identifier,
40
            $current,
41
            $quotaPolicy,
42 3
            (new DateTimeImmutable())->modify('+' . $this->ttl($key) . ' seconds')
43
        );
44
    }
45 4
46
    private function key(string $identifier, int $interval): string
47 4
    {
48 4
        return "{$this->keyPrefix}:{$interval}:$identifier";
49
    }
50
51
    private function ttl(string $key) : int
52
    {
53
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
54
    }
55
}
56