| Total Complexity | 6 | 
| Total Lines | 64 | 
| Duplicated Lines | 0 % | 
| Coverage | 100% | 
| Changes | 1 | ||
| Bugs | 0 | Features | 0 | 
| 1 | <?php | ||
| 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 | |
| 63 | } | ||
| 64 | |||
| 65 | /** | ||
| 66 | * Reset this rate limit. | ||
| 67 | */ | ||
| 68 | 1 | public function reset(): self | |
| 74 | } | ||
| 75 | } | ||
| 76 |