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

PredisRateLimiter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 33
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCurrent() 0 4 1
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 Predis\ClientInterface;
8
9
final class PredisRateLimiter extends AbstractTTLRateLimiter
10
{
11
    /** @var ClientInterface */
12
    private $predis;
13
14 5
    public function __construct(ClientInterface $predis, string $keyPrefix = '')
15
    {
16 5
        parent::__construct($keyPrefix);
17
18 5
        $this->predis = $predis;
19 5
    }
20
21 5
    protected function getCurrent(string $key): int
22
    {
23 5
        return (int) $this->predis->get($key);
24
    }
25
26 5
    protected function updateCounter(string $key, int $interval): int
27
    {
28 5
        $current = $this->predis->incr($key);
29
30 5
        if ($current === 1) {
31 5
            $this->predis->expire($key, $interval);
32
        }
33
34 5
        return $current;
35
    }
36
37 3
    protected function ttl(string $key): int
38
    {
39 3
        return max((int) ceil($this->predis->pttl($key) / 1000), 0);
40
    }
41
}
42