RateLimits::resetAt()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\LazyJsonPages\Services;
6
7
use Cerbero\LazyJsonPages\Data\RateLimit;
8
9
/**
10
 * The rate limits aggregator.
11
 */
12
final class RateLimits
13
{
14
    /**
15
     * The API rate limits to respect.
16
     *
17
     * @var RateLimit[]
18
     */
19
    private array $rateLimits = [];
20
21
    /**
22
     * Add the given rate limit.
23
     */
24 1
    public function add(int $requests, int $perSeconds): self
25
    {
26 1
        $this->rateLimits[] = new RateLimit($requests, $perSeconds);
27
28 1
        return $this;
29
    }
30
31
    /**
32
     * Hit the rate limits with a request.
33
     */
34 1
    public function hit(): self
35
    {
36 1
        foreach ($this->rateLimits as $rateLimit) {
37 1
            $rateLimit->hit();
38
        }
39
40 1
        return $this;
41
    }
42
43
    /**
44
     * Retrieve the number of requests allowed before the next rate limit.
45
     */
46 1
    public function threshold(): int
47
    {
48 1
        $threshold = INF;
49
50 1
        foreach ($this->rateLimits as $rateLimit) {
51 1
            $threshold = min($rateLimit->threshold(), $threshold);
52
        }
53
54 1
        return (int) $threshold;
55
    }
56
57
    /**
58
     * Retrieve the timestamp after which it is possible to send new requests.
59
     */
60 1
    public function resetAt(): float
61
    {
62 1
        $timestamp = 0.0;
63
64 1
        foreach ($this->rateLimits as $rateLimit) {
65 1
            if ($rateLimit->wasReached()) {
66 1
                $timestamp = max($rateLimit->resetsAt() ?? 0.0, $timestamp);
67
68 1
                $rateLimit->reset();
69
            }
70
        }
71
72 1
        return $timestamp;
73
    }
74
}
75