Debian Codegraph @

vendor/react/event-loop/src/Timer/Timers.php

raw
1 <?php
2
3 namespace React\EventLoop\Timer;
4
5 use React\EventLoop\TimerInterface;
6
7 /**
8 * A scheduler implementation that can hold multiple timer instances
9 *
10 * This class should only be used internally, see TimerInterface instead.
11 *
12 * @see TimerInterface
13 * @internal
14 */
15 final class Timers
16 {
17 private $time;
18 private $timers = array();
19 private $schedule = array();
20 private $sorted = true;
21 private $useHighResolution;
22
23 public function __construct()
24 {
25 // prefer high-resolution timer, available as of PHP 7.3+
26 $this->useHighResolution = \function_exists('hrtime');
27 }
28
29 public function updateTime()
30 {
31 return $this->time = $this->useHighResolution ? \hrtime(true) * 1e-9 : \microtime(true);
32 }
33
34 public function getTime()
35 {
36 return $this->time ?: $this->updateTime();
37 }
38
39 public function add(TimerInterface $timer)
40 {
41 $id = \spl_object_hash($timer);
42 $this->timers[$id] = $timer;
43 $this->schedule[$id] = $timer->getInterval() + $this->updateTime();
44 $this->sorted = false;
45 }
46
47 public function contains(TimerInterface $timer)
48 {
49 return isset($this->timers[\spl_object_hash($timer)]);
50 }
51
52 public function cancel(TimerInterface $timer)
53 {
54 $id = \spl_object_hash($timer);
55 unset($this->timers[$id], $this->schedule[$id]);
56 }
57
58 public function getFirst()
59 {
60 // ensure timers are sorted to simply accessing next (first) one
61 if (!$this->sorted) {
62 $this->sorted = true;
63 \asort($this->schedule);
64 }
65
66 return \reset($this->schedule);
67 }
68
69 public function isEmpty()
70 {
71 return \count($this->timers) === 0;
72 }
73
74 public function tick()
75 {
76 // ensure timers are sorted so we can execute in order
77 if (!$this->sorted) {
78 $this->sorted = true;
79 \asort($this->schedule);
80 }
81
82 $time = $this->updateTime();
83
84 foreach ($this->schedule as $id => $scheduled) {
85 // schedule is ordered, so loop until first timer that is not scheduled for execution now
86 if ($scheduled >= $time) {
87 break;
88 }
89
90 // skip any timers that are removed while we process the current schedule
91 if (!isset($this->schedule[$id]) || $this->schedule[$id] !== $scheduled) {
92 continue;
93 }
94
95 $timer = $this->timers[$id];
96 \call_user_func($timer->getCallback(), $timer);
97
98 // re-schedule if this is a periodic timer and it has not been cancelled explicitly already
99 if ($timer->isPeriodic() && isset($this->timers[$id])) {
100 $this->schedule[$id] = $timer->getInterval() + $time;
101 $this->sorted = false;
102 } else {
103 unset($this->timers[$id], $this->schedule[$id]);
104 }
105 }
106 }
107 }