Completed
Pull Request — master (#24)
by Julián
06:48
created

RedisRateLimiter::key()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use Redis;
8
9
final class RedisRateLimiter extends AbstractTTLRateLimiter
10
{
11
    /** @var Redis */
12
    private $redis;
13
14
    public function __construct(Redis $predis, string $keyPrefix = '')
15
    {
16
        if (!\extension_loaded('redis')) {
17
            throw new \RuntimeException('Redis extension is not loaded.');
18 5
        }
19
20 5
        parent::__construct($keyPrefix);
21 5
22 5
        $this->redis = $predis;
23
    }
24 2
25
    protected function getCurrent(string $key): int
26 2
    {
27
        return (int) $this->redis->get($key);
28 2
    }
29
30 2
    protected function updateCounter(string $key, int $interval): int
31 2
    {
32
        $current = $this->redis->incr($key);
33
34 2
        if ($current === 1) {
35 2
            $this->redis->expire($key, $interval);
36
        }
37 3
38
        return $current;
39 3
    }
40
41 3
    protected function ttl(string $key): int
42
    {
43 3
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
44 3
    }
45
}
46