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

PredisRateLimiter::ttl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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
    public function __construct(ClientInterface $predis, string $keyPrefix = '')
15
    {
16
        parent::__construct($keyPrefix);
17
18
        $this->predis = $predis;
19
    }
20
21
    protected function getCurrent(string $key): int
22
    {
23
        return (int) $this->predis->get($key);
24
    }
25
26
    protected function updateCounter(string $key, int $interval): int
27
    {
28
        $current = $this->predis->incr($key);
29
30
        if ($current === 1) {
31
            $this->predis->expire($key, $interval);
32
        }
33
34
        return $current;
35
    }
36
37
    protected function ttl(string $key): int
38
    {
39
        return max((int) ceil($this->predis->pttl($key) / 1000), 0);
40
    }
41
}
42