Chris@0
|
1 <?php
|
Chris@0
|
2 namespace GuzzleHttp\Promise;
|
Chris@0
|
3
|
Chris@0
|
4 /**
|
Chris@0
|
5 * A task queue that executes tasks in a FIFO order.
|
Chris@0
|
6 *
|
Chris@0
|
7 * This task queue class is used to settle promises asynchronously and
|
Chris@0
|
8 * maintains a constant stack size. You can use the task queue asynchronously
|
Chris@0
|
9 * by calling the `run()` function of the global task queue in an event loop.
|
Chris@0
|
10 *
|
Chris@0
|
11 * GuzzleHttp\Promise\queue()->run();
|
Chris@0
|
12 */
|
Chris@0
|
13 class TaskQueue implements TaskQueueInterface
|
Chris@0
|
14 {
|
Chris@0
|
15 private $enableShutdown = true;
|
Chris@0
|
16 private $queue = [];
|
Chris@0
|
17
|
Chris@0
|
18 public function __construct($withShutdown = true)
|
Chris@0
|
19 {
|
Chris@0
|
20 if ($withShutdown) {
|
Chris@0
|
21 register_shutdown_function(function () {
|
Chris@0
|
22 if ($this->enableShutdown) {
|
Chris@0
|
23 // Only run the tasks if an E_ERROR didn't occur.
|
Chris@0
|
24 $err = error_get_last();
|
Chris@0
|
25 if (!$err || ($err['type'] ^ E_ERROR)) {
|
Chris@0
|
26 $this->run();
|
Chris@0
|
27 }
|
Chris@0
|
28 }
|
Chris@0
|
29 });
|
Chris@0
|
30 }
|
Chris@0
|
31 }
|
Chris@0
|
32
|
Chris@0
|
33 public function isEmpty()
|
Chris@0
|
34 {
|
Chris@0
|
35 return !$this->queue;
|
Chris@0
|
36 }
|
Chris@0
|
37
|
Chris@0
|
38 public function add(callable $task)
|
Chris@0
|
39 {
|
Chris@0
|
40 $this->queue[] = $task;
|
Chris@0
|
41 }
|
Chris@0
|
42
|
Chris@0
|
43 public function run()
|
Chris@0
|
44 {
|
Chris@0
|
45 /** @var callable $task */
|
Chris@0
|
46 while ($task = array_shift($this->queue)) {
|
Chris@0
|
47 $task();
|
Chris@0
|
48 }
|
Chris@0
|
49 }
|
Chris@0
|
50
|
Chris@0
|
51 /**
|
Chris@0
|
52 * The task queue will be run and exhausted by default when the process
|
Chris@0
|
53 * exits IFF the exit is not the result of a PHP E_ERROR error.
|
Chris@0
|
54 *
|
Chris@0
|
55 * You can disable running the automatic shutdown of the queue by calling
|
Chris@0
|
56 * this function. If you disable the task queue shutdown process, then you
|
Chris@0
|
57 * MUST either run the task queue (as a result of running your event loop
|
Chris@0
|
58 * or manually using the run() method) or wait on each outstanding promise.
|
Chris@0
|
59 *
|
Chris@0
|
60 * Note: This shutdown will occur before any destructors are triggered.
|
Chris@0
|
61 */
|
Chris@0
|
62 public function disableShutdown()
|
Chris@0
|
63 {
|
Chris@0
|
64 $this->enableShutdown = false;
|
Chris@0
|
65 }
|
Chris@0
|
66 }
|