Completed
Push — master ( f8807b...5769db )
by Nikola
06:22
created

InMemoryRateLimiter::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 20
c 0
b 0
f 0
rs 9.6
ccs 4
cts 4
cp 1
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use DateTimeImmutable;
8
9
final class InMemoryRateLimiter implements RateLimiter
10
{
11
    /** @var array */
12
    private $store = [];
13
14
    public function handle(string $identifier, QuotaPolicy $quotaPolicy): Status
15
    {
16
        $key = "$identifier:{$quotaPolicy->getInterval()}:" . floor(time() / $quotaPolicy->getInterval());
17
18
        if (!isset($this->store[$key])) {
19
            $this->store[$key] = [
20
                'current' => 1,
21
                'expires' => time() + $quotaPolicy->getInterval(),
22
            ];
23
        } elseif ($this->store[$key]['current'] <= $quotaPolicy->getQuota()) {
24
            $this->store[$key]['current']++;
25 10
        }
26
27
        return Status::from(
28 10
            $identifier,
29 10
            $this->store[$key]['current'],
30
            $quotaPolicy,
31 10
            new DateTimeImmutable('@' . $this->store[$key]['expires'])
32
        );
33
    }
34
}
35