Debian Codegraph @

vendor/ipl/scheduler/src/Common/Timers.php

raw
1 <?php
2
3 namespace ipl\Scheduler\Common;
4
5 use Ramsey\Uuid\UuidInterface;
6 use React\EventLoop\TimerInterface;
7 use SplObjectStorage;
8
9 /**
10 * Tracks scheduled {@see TimerInterface timers} per UUID
11 *
12 * Provides helpers to attach and detach event-loop timers keyed by a {@see UuidInterface}.
13 */
14 trait Timers
15 {
16 /** @var SplObjectStorage<UuidInterface, TimerInterface> */
17 protected SplObjectStorage $timers;
18
19 /**
20 * Set a timer for the given UUID
21 *
22 * **Example Usage:**
23 *
24 * $timers->attachTimer($uuid, Loop::addTimer($interval, $callback));
25 *
26 * @param UuidInterface $uuid
27 * @param TimerInterface $timer
28 *
29 * @return $this
30 */
31 protected function attachTimer(UuidInterface $uuid, TimerInterface $timer): static
32 {
33 $this->timers->offsetSet($uuid, $timer);
34
35 return $this;
36 }
37
38 /**
39 * Detach and return the timer for the given UUID, if any
40 *
41 * **Example Usage:**
42 *
43 * Loop::cancelTimer($timers->detachTimer($uuid));
44 *
45 * @param UuidInterface $uuid
46 *
47 * @return ?TimerInterface
48 */
49 protected function detachTimer(UuidInterface $uuid): ?TimerInterface
50 {
51 if (! $this->timers->offsetExists($uuid)) {
52 return null;
53 }
54
55 $timer = $this->timers->offsetGet($uuid);
56
57 $this->timers->offsetUnset($uuid);
58
59 return $timer;
60 }
61 }