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

MemcachedRateLimiter::updateCounter()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 3
nc 4
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use Memcached;
8
9
final class MemcachedRateLimiter extends AbstractElapsedTimeRateLimiter
10
{
11
    private const MEMCACHED_SECONDS_LIMIT = 2592000; // Number of seconds in 30 days
12
13
    /** @var Memcached */
14
    private $memcached;
15
16
    public function __construct(Memcached $memcached, string $keyPrefix = '')
17
    {
18
        if ($memcached->getOption(Memcached::OPT_BINARY_PROTOCOL) !== 1) {
19
            throw new \RuntimeException('Memcached "OPT_BINARY_PROTOCOL" option should be set to "true".');
20
        }
21
22
        parent::__construct($keyPrefix);
23
24
        $this->memcached = $memcached;
25
    }
26
27
    protected function getCurrent(string $valueKey): int
28
    {
29
        return (int) $this->memcached->get($valueKey);
30
    }
31
32
    protected function updateCounter(string $valueKey, string $timeKey, int $interval): int
33
    {
34
        $current = $this->memcached->increment($valueKey, 1, 1, $this->intervalToMemcachedTime($interval));
35
36
        if ($current === 1) {
37
            $this->memcached->add($timeKey, \time(), $this->intervalToMemcachedTime($interval));
38
        }
39
40
        return $current === false ? 1 : $current;
41
    }
42
43
    protected function getElapsedTime(string $timeKey): int
44
    {
45
        return \time() - (int) $this->memcached->get($timeKey);
46
    }
47
48
    /**
49
     * Interval to Memcached expiration time.
50
     *
51
     * @see https://www.php.net/manual/en/memcached.expiration.php
52
     *
53
     * @param int $interval
54
     *
55
     * @return int
56
     */
57
    private function intervalToMemcachedTime(int $interval): int
58
    {
59
        return $interval <= self::MEMCACHED_SECONDS_LIMIT ? $interval : \time() + $interval;
60
    }
61
}
62