CancellationQueue.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace React\Promise;
  3. class CancellationQueue
  4. {
  5. private $started = false;
  6. private $queue = [];
  7. public function __invoke()
  8. {
  9. if ($this->started) {
  10. return;
  11. }
  12. $this->started = true;
  13. $this->drain();
  14. }
  15. public function enqueue($cancellable)
  16. {
  17. if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) {
  18. return;
  19. }
  20. $length = \array_push($this->queue, $cancellable);
  21. if ($this->started && 1 === $length) {
  22. $this->drain();
  23. }
  24. }
  25. private function drain()
  26. {
  27. for ($i = key($this->queue); isset($this->queue[$i]); $i++) {
  28. $cancellable = $this->queue[$i];
  29. $exception = null;
  30. try {
  31. $cancellable->cancel();
  32. } catch (\Throwable $exception) {
  33. } catch (\Exception $exception) {
  34. }
  35. unset($this->queue[$i]);
  36. if ($exception) {
  37. throw $exception;
  38. }
  39. }
  40. $this->queue = [];
  41. }
  42. }