FulfilledPromise.php 2.0 KB

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