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

ApcuRateLimiter::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
final class ApcuRateLimiter extends AbstractElapsedTimeRateLimiter
8
{
9
    public function __construct(string $keyPrefix = '')
10
    {
11
        if (!\extension_loaded('apcu')) {
12
            throw new \RuntimeException('APCu extension is not loaded.');
13
        }
14
15
        if (\ini_get('apc.use_request_time') === '1') {
16
            throw new \RuntimeException('APCu ini configuration "apc.use_request_time" should be set to "0".');
17
        }
18
19
        parent::__construct($keyPrefix);
20
    }
21
22
    protected function getCurrent(string $valueKey): int
23
    {
24
        return (int) \apcu_fetch($valueKey);
25
    }
26
27
    protected function updateCounter(string $valueKey, string $timeKey, int $interval): int
28
    {
29
        $current = \apcu_inc($valueKey, 1, $success, $interval);
30
31
        if ($current === 1) {
32
            \apcu_store($timeKey, \time(), $interval);
33
        }
34
35
        return $current === false ? 1 : $current;
36
    }
37
38
    protected function getElapsedTime(string $timeKey): int
39
    {
40
        return \time() - (int) \apcu_fetch($timeKey);
41
    }
42
}
43