RejectedPromise.php 2.2 KB

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