Completed
Pull Request — master (#24)
by Julián
04:37
created

RedisRateLimiter::limit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A RedisRateLimiter::getCurrent() 0 4 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 5
    public function __construct(Redis $predis, string $keyPrefix = '')
15
    {
16 5
        if (!\extension_loaded('redis')) {
17
            throw new \RuntimeException('Redis extension is not loaded.');
18
        }
19
20 5
        parent::__construct($keyPrefix);
21
22 5
        $this->redis = $predis;
23 5
    }
24
25 5
    protected function getCurrent(string $key): int
26
    {
27 5
        return (int) $this->redis->get($key);
28
    }
29
30 5
    protected function updateCounter(string $key, int $interval): int
31
    {
32 5
        $current = $this->redis->incr($key);
33
34 5
        if ($current === 1) {
35 5
            $this->redis->expire($key, $interval);
36
        }
37
38 5
        return $current;
39
    }
40
41 3
    protected function ttl(string $key): int
42
    {
43 3
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
44
    }
45
}
46