Test Setup Failed
Push — master ( 8c5f4b...dcf915 )
by Alexpts
03:11
created

MemoryAdapter::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace PTS\RateLimiter\Adapter;
5
6
use PTS\RateLimiter\StoreInterface;
7
8
class MemoryAdapter implements StoreInterface
9
{
10
    protected int $cleanExpired = 30;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
11
    protected int $lastClean = 0;
12
13
    protected array $store = [];
14
    protected array $ttlKeys = [];
15
16 16
    public function get(string $key): int
17
    {
18 16
        $this->isNeedCleanExpired() && $this->cleanExpired();
19 16
        return $this->store[$key] ?? 0;
20
    }
21
22 16
    public function __construct(int $cleanExpired = 30)
23
    {
24 16
        $this->cleanExpired = $cleanExpired;
25 16
        $this->lastClean = time();
26 16
    }
27
28 14
    public function inc(string $key, int $ttl = 60): int
29
    {
30 14
        $value = $this->get($key);
31 14
        $this->store[$key] = ++$value;
32
33 14
        if ($value === 1) {
34 14
            $this->ttlKeys[$key] = time() + $ttl;
35
        }
36
37 14
        return $value;
38
    }
39
40 12
    public function reset(string $key): bool
41
    {
42 12
        unset($this->store[$key], $this->ttlKeys[$key]);
43 12
        return true;
44
    }
45
46 6
    public function isExceeded(string $key, int $max): bool
47
    {
48 6
        $value = $this->get($key);
49 6
        return $value >= $max;
50
    }
51
52 16
    protected function isNeedCleanExpired(): bool
53
    {
54 16
        return ($this->lastClean + $this->cleanExpired) <= time();
55
    }
56
57 1
    protected function cleanExpired(): void
58
    {
59 1
        $current = time();
60
61
        $this->ttlKeys = array_filter ($this->ttlKeys, function (int $time, string $key) use ($current) {
62 1
            $isExpired = $time < $current;
63 1
            if ($isExpired) {
64 1
                unset($this->store[$key]);
65
            }
66
67 1
            return !$isExpired;
68 1
        }, ARRAY_FILTER_USE_BOTH);
69 1
    }
70
71 2
    public function ttl(string $key): ?int
72
    {
73 2
        if (array_key_exists($key, $this->ttlKeys)) {
74 2
            $ttl = $this->ttlKeys[$key] - time();
75 2
            return $ttl > 0 ? $ttl : 0;
76
        }
77
78 1
        return null;
79
    }
80
81
}
82