Lines 100.00% 17 / 17
Methods 100.00% 4 / 4
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 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
17final 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}