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

AbstractElapsedTimeRateLimiter::limit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 2
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