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

RedisRateLimiter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 37
ccs 14
cts 15
cp 0.9333
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getCurrent() 0 4 1
A __construct() 0 10 2
A updateCounter() 0 10 2
A ttl() 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