Issues (11)

src/Quota.php (1 issue)

1
<?php
2
3
namespace Zenstruck\Governator;
4
5
use Zenstruck\Governator\Exception\QuotaExceeded;
6
7
/**
8
 * Information on the current state of the throttle.
9
 *
10
 * @author Kevin Bond <[email protected]>
11
 */
12
final class Quota
13
{
14
    private Key $key;
15
    private Counter $counter;
16
17 113
    public function __construct(Key $key, Counter $counter)
18
    {
19 113
        $this->key = $key;
20 113
        $this->counter = $counter;
21 113
    }
22
23
    /**
24
     * @return Key The key used to create the throttle
25
     */
26 5
    public function key(): Key
27
    {
28 5
        return $this->key;
29
    }
30
31
    /**
32
     * @return string The throttle's unique identifier
33
     */
34 18
    public function resource(): string
35
    {
36 18
        return $this->key->resource();
37
    }
38
39
    /**
40
     * @return int The throttle's limit
41
     */
42 113
    public function limit(): int
43
    {
44 113
        return $this->key->limit();
45
    }
46
47
    /**
48
     * @return int The number of throttle hits
49
     */
50 108
    public function hits(): int
51
    {
52 108
        return $this->counter->hits();
53
    }
54
55
    /**
56
     * @return int Number of allowed hits before the throttle resets (never negative)
57
     */
58 93
    public function remaining(): int
59
    {
60 93
        return \max(0, $this->limit() - $this->hits());
61
    }
62
63
    /**
64
     * @return \DateTimeImmutable When the throttle resets (never in the past)
65
     */
66 18
    public function resetsAt(): \DateTimeImmutable
67
    {
68 18
        return \DateTimeImmutable::createFromFormat('U', $this->counter->resetsAt());
0 ignored issues
show
Bug Best Practice introduced by
The expression return DateTimeImmutable...s->counter->resetsAt()) could return the type false which is incompatible with the type-hinted return DateTimeImmutable. Consider adding an additional type-check to rule them out.
Loading history...
69
    }
70
71
    /**
72
     * @return int Number of seconds until the throttle resets (never negative)
73
     */
74 97
    public function resetsIn(): int
75
    {
76 97
        return $this->counter->resetsIn();
77
    }
78
79 103
    public function hasBeenExceeded(): bool
80
    {
81 103
        return $this->counter->hits() > $this->limit();
82
    }
83
84
    /**
85
     * @throws QuotaExceeded If the throttle has been exceeded
86
     */
87 93
    public function check(): self
88
    {
89 93
        if ($this->hasBeenExceeded()) {
90 39
            throw new QuotaExceeded($this);
91
        }
92
93 92
        return $this;
94
    }
95
}
96