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

AbstractElapsedTimeRateLimiter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

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

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A limit() 0 13 2
A limitSilently() 0 18 2
A valueKey() 0 4 1
A timeKey() 0 4 1
getCurrent() 0 1 ?
updateCounter() 0 1 ?
getElapsedTime() 0 1 ?
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use RateLimit\Exception\LimitExceeded;
8
9
abstract class AbstractElapsedTimeRateLimiter implements RateLimiter, SilentRateLimiter
10
{
11
    /** @var string */
12
    private $keyPrefix;
13
14
    public function __construct(string $keyPrefix = '')
15
    {
16
        $this->keyPrefix = $keyPrefix;
17
    }
18
19
    final public function limit(string $identifier, Rate $rate): void
20
    {
21
        $interval = $rate->getInterval();
22
        $valueKey = $this->valueKey($identifier, $interval);
23
        $timeKey = $this->timeKey($identifier, $interval);
24
25
        $current = $this->getCurrent($valueKey);
26
        if ($current >= $rate->getOperations()) {
27
            throw LimitExceeded::for($identifier, $rate);
28
        }
29
30
        $this->updateCounter($valueKey, $timeKey, $rate->getInterval());
31
    }
32
33
    final public function limitSilently(string $identifier, Rate $rate): Status
34
    {
35
        $interval = $rate->getInterval();
36
        $valueKey = $this->valueKey($identifier, $interval);
37
        $timeKey = $this->timeKey($identifier, $interval);
38
39
        $current = $this->getCurrent($valueKey);
40
        if ($current <= $rate->getOperations()) {
41
            $current = $this->updateCounter($valueKey, $timeKey, $interval);
42
        }
43
44
        return Status::from(
45
            \sprintf('%s%s', $this->keyPrefix, $identifier),
46
            $current,
47
            $rate->getOperations(),
48
            \time() + \max(0, $interval - $this->getElapsedTime($timeKey))
49
        );
50
    }
51
52
    private function valueKey(string $identifier, int $interval): string
53
    {
54
        return \sprintf('%s%s:value:%d', $this->keyPrefix, $identifier, $interval);
55
    }
56
57
    private function timeKey(string $identifier, int $interval): string
58
    {
59
        return \sprintf('%s%s:time:%d', $this->keyPrefix, $identifier, $interval);
60
    }
61
62
    abstract protected function getCurrent(string $valueKey): int;
63
64
    abstract protected function updateCounter(string $valueKey, string $timeKey, int $interval): int;
65
66
    abstract protected function getElapsedTime(string $timeKey): int;
67
}
68