Lines
100.00%
17 / 17
Functions and Methods
100.00%
4 / 4
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| RevoltTimers | 100.00% | 17 / 17 | 100.00% | 4 / 4 | 6 | 100.00% | 1 / 1 | |||
| startTimer | 100.00% | 8 / 8 | 100.00% | 1 / 1 | 1 | |||||
| waitFor | 100.00% | 7 / 7 | 100.00% | 1 / 1 | 3 | |||||
| timeout | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| delay | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Support\Time; | |
| 6 | ||
| 7 | use Amp\Cancellation; | |
| 8 | use Amp\TimeoutCancellation; | |
| 9 | use Closure; | |
| 10 | use Revolt\EventLoop; | |
| 11 | use Stewart\Contracts\Time\Duration; | |
| 12 | use Stewart\Contracts\Time\PendingWait; | |
| 13 | ||
| 14 | use function Amp\delay; | |
| 15 | ||
| 16 | /** @internal */ | |
| 17 | final class RevoltTimers implements Timers, Deadlines | |
| 18 | { | |
| 19 | public function startTimer(Duration $delay, Closure $callback): TimerHandle | |
| 20 | { | |
| 21 | $handle = new RevoltTimerHandle(); | |
| 22 | ||
| 23 | $identifier = EventLoop::delay($delay->toSeconds(), static function () use ($handle, $callback): void { | |
| 24 | $handle->markFired(); | |
| 25 | ||
| 26 | $callback(); | |
| 27 | }); | |
| 28 | ||
| 29 | EventLoop::unreference($identifier); | |
| 30 | ||
| 31 | $handle->attachWatcher($identifier); | |
| 32 | ||
| 33 | return $handle; | |
| 34 | } | |
| 35 | ||
| 36 | /** | |
| 37 | * @template T | |
| 38 | * @param Closure(PendingWait<T>): (Closure(): void) $arm | |
| 39 | * @return T|null | |
| 40 | */ | |
| 41 | public function waitFor(Closure $arm, ?Duration $timeout = null): mixed | |
| 42 | { | |
| 43 | /** @var DeferredWait<T> $wait */ | |
| 44 | $wait = new DeferredWait(); | |
| 45 | $teardown = $arm($wait); | |
| 46 | // Referenced, unlike startTimer(), so a wait in {main} keeps the loop running until it ends. | |
| 47 | $timeoutWatcher = $timeout === null ? null : EventLoop::delay($timeout->toSeconds(), $wait->expire(...)); | |
| 48 | ||
| 49 | try { | |
| 50 | return $wait->awaitOutcome(); | |
| 51 | } finally { | |
| 52 | if ($timeoutWatcher !== null) { | |
| 53 | EventLoop::cancel($timeoutWatcher); | |
| 54 | } | |
| 55 | ||
| 56 | $teardown(); | |
| 57 | } | |
| 58 | } | |
| 59 | ||
| 60 | public function timeout(Duration $limit): Cancellation | |
| 61 | { | |
| 62 | return new TimeoutCancellation($limit->toSeconds()); | |
| 63 | } | |
| 64 | ||
| 65 | public function delay(Duration $wait, ?Cancellation $cancellation = null): void | |
| 66 | { | |
| 67 | delay($wait->toSeconds(), cancellation: $cancellation); | |
| 68 | } | |
| 69 | } |