Chris@0: run(); Chris@0: */ Chris@0: class TaskQueue implements TaskQueueInterface Chris@0: { Chris@0: private $enableShutdown = true; Chris@0: private $queue = []; Chris@0: Chris@0: public function __construct($withShutdown = true) Chris@0: { Chris@0: if ($withShutdown) { Chris@0: register_shutdown_function(function () { Chris@0: if ($this->enableShutdown) { Chris@0: // Only run the tasks if an E_ERROR didn't occur. Chris@0: $err = error_get_last(); Chris@0: if (!$err || ($err['type'] ^ E_ERROR)) { Chris@0: $this->run(); Chris@0: } Chris@0: } Chris@0: }); Chris@0: } Chris@0: } Chris@0: Chris@0: public function isEmpty() Chris@0: { Chris@0: return !$this->queue; Chris@0: } Chris@0: Chris@0: public function add(callable $task) Chris@0: { Chris@0: $this->queue[] = $task; Chris@0: } Chris@0: Chris@0: public function run() Chris@0: { Chris@0: /** @var callable $task */ Chris@0: while ($task = array_shift($this->queue)) { Chris@0: $task(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * The task queue will be run and exhausted by default when the process Chris@0: * exits IFF the exit is not the result of a PHP E_ERROR error. Chris@0: * Chris@0: * You can disable running the automatic shutdown of the queue by calling Chris@0: * this function. If you disable the task queue shutdown process, then you Chris@0: * MUST either run the task queue (as a result of running your event loop Chris@0: * or manually using the run() method) or wait on each outstanding promise. Chris@0: * Chris@0: * Note: This shutdown will occur before any destructors are triggered. Chris@0: */ Chris@0: public function disableShutdown() Chris@0: { Chris@0: $this->enableShutdown = false; Chris@0: } Chris@0: }