Completed
Push — master ( 624dd7...696191 )
by Nikola
04:34
created

RedisRateLimiter::updateCounter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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