InMemoryRateLimiter::increment()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of the Rate Limit package.
4
 *
5
 * Copyright (c) Nikola Posa
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
namespace RateLimit;
12
13
/**
14
 * @author Nikola Posa <[email protected]>
15
 */
16
final class InMemoryRateLimiter extends AbstractRateLimiter
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $store = [];
22
23 10
    protected function get($key, $default)
24
    {
25
        if (
26 10
            !$this->has($key)
27 10
            || $this->hasExpired($key)
28
        ) {
29 10
            return $default;
30
        }
31
32 9
        return $this->store[$key]['current'];
33
    }
34
35 10
    protected function init($key)
36
    {
37 10
        $this->store[(string)$key] = [
38 10
            'current' => 1,
39 10
            'expires' => time() + $this->window,
40
        ];
41 10
    }
42
43 1
    protected function increment($key)
44
    {
45 1
        $this->store[(string)$key]['current']++;
46 1
    }
47
48 8
    protected function ttl($key)
49
    {
50 8
        $key = (string)$key;
51 8
        if (!isset($this->store[$key])) {
52 1
            return 0;
53
        }
54
55 7
        return max($this->store[$key]['expires'] - time(), 0);
56
    }
57
58 10
    private function has($key)
59
    {
60 10
        return array_key_exists((string)$key, $this->store);
61
    }
62
63 9
    private function hasExpired($key)
64
    {
65 9
        return time() > $this->store[(string)$key]['expires'];
66
    }
67
}
68