FulfilledPromise.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace GuzzleHttp\Promise;
  3. /**
  4. * A promise that has been fulfilled.
  5. *
  6. * Thenning off of this promise will invoke the onFulfilled callback
  7. * immediately and ignore other callbacks.
  8. */
  9. class FulfilledPromise implements PromiseInterface
  10. {
  11. private $value;
  12. public function __construct($value)
  13. {
  14. if (method_exists($value, 'then')) {
  15. throw new \InvalidArgumentException(
  16. 'You cannot create a FulfilledPromise with a promise.');
  17. }
  18. $this->value = $value;
  19. }
  20. public function then(
  21. callable $onFulfilled = null,
  22. callable $onRejected = null
  23. ) {
  24. // Return itself if there is no onFulfilled function.
  25. if (!$onFulfilled) {
  26. return $this;
  27. }
  28. $queue = queue();
  29. $p = new Promise([$queue, 'run']);
  30. $value = $this->value;
  31. $queue->add(static function () use ($p, $value, $onFulfilled) {
  32. if ($p->getState() === self::PENDING) {
  33. try {
  34. $p->resolve($onFulfilled($value));
  35. } catch (\Throwable $e) {
  36. $p->reject($e);
  37. } catch (\Exception $e) {
  38. $p->reject($e);
  39. }
  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. return $unwrap ? $this->value : null;
  51. }
  52. public function getState()
  53. {
  54. return self::FULFILLED;
  55. }
  56. public function resolve($value)
  57. {
  58. if ($value !== $this->value) {
  59. throw new \LogicException("Cannot resolve a fulfilled promise");
  60. }
  61. }
  62. public function reject($reason)
  63. {
  64. throw new \LogicException("Cannot reject a fulfilled promise");
  65. }
  66. public function cancel()
  67. {
  68. // pass
  69. }
  70. }