Passed
Push — master ( 2d675e...7fc076 )
by BENOIT
07:13 queued 04:13
created

ArrayStorage   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 12
eloc 20
c 2
b 0
f 0
dl 0
loc 70
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A increment() 0 11 3
A getRemainingCalls() 0 3 1
A __construct() 0 4 1
A getRemainingTime() 0 7 2
A decrement() 0 5 2
A isExpired() 0 7 2
A reset() 0 4 1
1
<?php
2
3
namespace BenTools\FunnelHttpClient\Storage;
4
5
final class ArrayStorage implements ThrottleStorageInterface
6
{
7
    private int $currentRequests = 0;
8
9
    private float|null $startedAt = null;
10
11
    public function __construct(
12
        private int $maxRequests,
13
        private float $timeWindow
14
    ) {
15
    }
16
17
    /**
18
     * @inheritDoc
19
     */
20
    public function getRemainingCalls(): int
21
    {
22
        return \max(0, ($this->maxRequests - $this->currentRequests));
23
    }
24
25
    /**
26
     * @inheritDoc
27
     */
28
    public function getRemainingTime(): float
29
    {
30
        if (null === $this->startedAt) {
31
            return 0;
32
        }
33
34
        return \max(0, ($this->startedAt + $this->timeWindow) - \microtime(true));
35
    }
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function increment(): void
41
    {
42
        if ($this->isExpired()) {
43
            $this->reset();
44
        }
45
46
        if (null === $this->startedAt) {
47
            $this->startedAt = \microtime(true);
48
        }
49
50
        $this->currentRequests++;
51
    }
52
53
    public function decrement(): void
54
    {
55
        $this->currentRequests--;
56
        if ($this->currentRequests <= 0) {
57
            $this->reset();
58
        }
59
    }
60
61
62
    private function reset(): void
63
    {
64
        $this->currentRequests = 0;
65
        $this->startedAt = null;
66
    }
67
68
    private function isExpired(): bool
69
    {
70
        if (null === $this->startedAt) {
71
            return false;
72
        }
73
74
        return \microtime(true) > ($this->startedAt + $this->timeWindow);
75
    }
76
}
77