Passed
Branch feature/second-release (e9200f)
by Andrea Marco
13:37
created

RateLimit::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\LazyJsonPages\Data;
6
7
/**
8
 * The API rate limit to respect.
9
 */
10
final class RateLimit
11
{
12
    /**
13
     * The number of requests sent before this rate limit resets.
14
     */
15
    private int $hits = 0;
16
17
    /**
18
     * The timestamp when this rate limit resets.
19
     */
20
    private ?float $resetsAt = null;
21
22
    /**
23
     * Instantiate the class.
24
     */
25 1
    public function __construct(
26
        public readonly int $requests,
27
        public readonly int $perSeconds,
28 1
    ) {}
29
30
    /**
31
     * Update the requests sent before this rate limit resets.
32
     */
33 1
    public function hit(): self
34
    {
35 1
        $this->hits++;
36 1
        $this->resetsAt ??= microtime(true) + $this->perSeconds;
37
38 1
        return $this;
39
    }
40
41
    /**
42
     * Retrieve the number of requests allowed before this rate limit resets.
43
     */
44 1
    public function threshold(): int
45
    {
46 1
        return $this->requests - $this->hits;
47
    }
48
49
    /**
50
     * Determine whether this rate limit was reached.
51
     */
52 1
    public function wasReached(): bool
53
    {
54 1
        return $this->hits == $this->requests;
55
    }
56
57
    /**
58
     * Retrieve the timestamp when this rate limit resets.
59
     */
60 1
    public function resetsAt(): ?float
61
    {
62 1
        return $this->resetsAt;
63
    }
64
65
    /**
66
     * Reset this rate limit.
67
     */
68 1
    public function reset(): self
69
    {
70 1
        $this->hits = 0;
71 1
        $this->resetsAt = null;
72
73 1
        return $this;
74
    }
75
}
76