RejectedPromise.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace GuzzleHttp\Promise;
  3. /**
  4. * A promise that has been rejected.
  5. *
  6. * Thenning off of this promise will invoke the onRejected callback
  7. * immediately and ignore other callbacks.
  8. */
  9. class RejectedPromise implements PromiseInterface
  10. {
  11. private $reason;
  12. /** @var Promise|null */
  13. private $promise;
  14. /** @var callable|null */
  15. private $onRejected;
  16. public function __construct($reason)
  17. {
  18. if (is_object($reason) && method_exists($reason, 'then')) {
  19. throw new \InvalidArgumentException(
  20. 'You cannot create a RejectedPromise with a promise.'
  21. );
  22. }
  23. $this->reason = $reason;
  24. }
  25. public function then(
  26. callable $onFulfilled = null,
  27. callable $onRejected = null
  28. ) {
  29. // If there's no onRejected callback then just return self.
  30. if (!$onRejected) {
  31. return $this;
  32. }
  33. $this->onRejected = $onRejected;
  34. $queue = Utils::queue();
  35. $reason = $this->reason;
  36. $p = $this->promise = new Promise([$queue, 'run']);
  37. $queue->add(static function () use ($p, $reason, $onRejected) {
  38. if (Is::pending($p)) {
  39. self::callHandler($p, $reason, $onRejected);
  40. }
  41. });
  42. return $p;
  43. }
  44. public function otherwise(callable $onRejected)
  45. {
  46. return $this->then(null, $onRejected);
  47. }
  48. public function wait($unwrap = true, $defaultDelivery = null)
  49. {
  50. if ($unwrap) {
  51. throw Create::exceptionFor($this->reason);
  52. }
  53. // Don't run the queue to avoid deadlocks, instead directly reject the promise.
  54. if ($this->promise && Is::pending($this->promise)) {
  55. self::callHandler($this->promise, $this->reason, $this->onRejected);
  56. }
  57. return null;
  58. }
  59. public function getState()
  60. {
  61. return self::REJECTED;
  62. }
  63. public function resolve($value)
  64. {
  65. throw new \LogicException("Cannot resolve a rejected promise");
  66. }
  67. public function reject($reason)
  68. {
  69. if ($reason !== $this->reason) {
  70. throw new \LogicException("Cannot reject a rejected promise");
  71. }
  72. }
  73. public function cancel()
  74. {
  75. // pass
  76. }
  77. private static function callHandler(Promise $promise, $reason, callable $handler)
  78. {
  79. try {
  80. $promise->resolve($handler($reason));
  81. } catch (\Throwable $e) {
  82. $promise->reject($e);
  83. } catch (\Exception $e) {
  84. $promise->reject($e);
  85. }
  86. }
  87. }