Completed
Pull Request — master (#24)
by Julián
07:27
created

MemcachedRateLimiter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 37
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A getCurrent() 0 4 1
A updateCounter() 0 10 3
A getElapsedTime() 0 4 1
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
    /** @var Memcached */
12
    private $memcached;
13
14
    public function __construct(Memcached $memcached, string $keyPrefix = '')
15
    {
16
        if ($memcached->getOption(Memcached::OPT_BINARY_PROTOCOL) !== 1) {
17
            throw new \RuntimeException('Memcached "OPT_BINARY_PROTOCOL" option should be set to "true".');
18
        }
19
20
        parent::__construct($keyPrefix);
21
22
        $this->memcached = $memcached;
23
    }
24
25
    protected function getCurrent(string $valueKey): int
26
    {
27
        return (int) $this->memcached->get($valueKey);
28
    }
29
30
    protected function updateCounter(string $valueKey, string $timeKey, int $interval): int
31
    {
32
        $current = $this->memcached->increment($valueKey, 1, 1, $interval);
33
34
        if ($current === 1) {
35
            $this->memcached->add($timeKey, \time(), $interval);
36
        }
37
38
        return $current === false ? 1 : $current;
39
    }
40
41
    protected function getElapsedTime(string $timeKey): int
42
    {
43
        return \time() - (int) $this->memcached->get($timeKey);
44
    }
45
}
46