Completed
Push — master ( c9b2ac...f80d0f )
by Nikola
33:36 queued 32:26
created

RedisRateLimiter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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 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
47
    {
48 3
        return "{$this->keyPrefix}:{$interval}:$identifier";
49
    }
50
51 3
    private function ttl(string $key): int
52
    {
53 3
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
54
    }
55
}
56