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

InMemoryRateLimiter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 26
c 0
b 0
f 0
wmc 3
lcom 1
cbo 2
rs 10
ccs 5
cts 5
cp 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 20 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