Completed
Push — master ( f80d0f...3008ec )
by Nikola
08:08
created

RedisRateLimiter::updateCounter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 2
nc 2
nop 2
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use DateTimeImmutable;
8
use RateLimit\Exception\LimitExceeded;
9
use Redis;
10
11
final class RedisRateLimiter implements RateLimiter, SilentRateLimiter
12
{
13
    /** @var Redis */
14
    private $redis;
15
16
    /** @var string */
17
    private $keyPrefix;
18 3
19
    public function __construct(Redis $redis, string $keyPrefix = '')
20 3
    {
21 3
        $this->redis = $redis;
22 3
        $this->keyPrefix = $keyPrefix;
23
    }
24 3
25
    public function limit(string $identifier, Rate $rate): void
26 3
    {
27
        $key = $this->key($identifier, $rate->getInterval());
28 3
29
        $current = $this->getCurrent($key);
30 3
31 3
        if ($current > $rate->getOperations()) {
32
            throw LimitExceeded::for($identifier, $rate);
33 3
        }
34 3
35
        $this->updateCounter($key, $rate->getInterval());
36
    }
37
38 3
    public function limitSilently(string $identifier, Rate $rate): Status
39 3
    {
40 3
        $key = $this->key($identifier, $rate->getInterval());
41 3
42 3
        $current = $this->getCurrent($key);
43
44
        if ($current <= $rate->getOperations()) {
45
            $current = $this->updateCounter($key, $rate->getInterval());
46 3
        }
47
48 3
        return Status::from(
49
            $identifier,
50
            $current,
51 3
            $rate,
52
            (new DateTimeImmutable())->modify('+' . $this->ttl($key) . ' seconds')
53 3
        );
54
    }
55
56
    private function key(string $identifier, int $interval): string
57
    {
58
        return "{$this->keyPrefix}:{$interval}:$identifier";
59
    }
60
61
    private function getCurrent(string $key): int
62
    {
63
        return (int) $this->redis->get($key);
64
    }
65
66
    private function updateCounter(string $key, int $interval): int
67
    {
68
        $current = $this->redis->incr($key);
69
70
        if ($current === 1) {
71
            $this->redis->expire($key, $interval);
72
        }
73
74
        return $current;
75
    }
76
77
    private function ttl(string $key): int
78
    {
79
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
80
    }
81
}
82