1: <?php
2:
3: namespace React\EventLoop\Tick;
4:
5: use React\EventLoop\LoopInterface;
6: use SplQueue;
7:
8: class FutureTickQueue
9: {
10: private $eventLoop;
11: private $queue;
12:
13: /**
14: * @param LoopInterface $eventLoop The event loop passed as the first parameter to callbacks.
15: */
16: public function __construct(LoopInterface $eventLoop)
17: {
18: $this->eventLoop = $eventLoop;
19: $this->queue = new SplQueue();
20: }
21:
22: /**
23: * Add a callback to be invoked on a future tick of the event loop.
24: *
25: * Callbacks are guaranteed to be executed in the order they are enqueued.
26: *
27: * @param callable $listener The callback to invoke.
28: */
29: public function add(callable $listener)
30: {
31: $this->queue->enqueue($listener);
32: }
33:
34: /**
35: * Flush the callback queue.
36: */
37: public function tick()
38: {
39: // Only invoke as many callbacks as were on the queue when tick() was called.
40: $count = $this->queue->count();
41:
42: while ($count--) {
43: call_user_func(
44: $this->queue->dequeue(),
45: $this->eventLoop
46: );
47: }
48: }
49:
50: /**
51: * Check if the next tick queue is empty.
52: *
53: * @return boolean
54: */
55: public function isEmpty()
56: {
57: return $this->queue->isEmpty();
58: }
59: }
60: