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