Promise.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\Event;
  4. use Exception;
  5. /**
  6. * An implementation of the Promise pattern.
  7. *
  8. * A promise represents the result of an asynchronous operation.
  9. * At any given point a promise can be in one of three states:
  10. *
  11. * 1. Pending (the promise does not have a result yet).
  12. * 2. Fulfilled (the asynchronous operation has completed with a result).
  13. * 3. Rejected (the asynchronous operation has completed with an error).
  14. *
  15. * To get a callback when the operation has finished, use the `then` method.
  16. *
  17. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  18. * @author Evert Pot (http://evertpot.com/)
  19. * @license http://sabre.io/license/ Modified BSD License
  20. *
  21. * @psalm-template TReturn
  22. */
  23. class Promise
  24. {
  25. /**
  26. * The asynchronous operation is pending.
  27. */
  28. public const PENDING = 0;
  29. /**
  30. * The asynchronous operation has completed, and has a result.
  31. */
  32. public const FULFILLED = 1;
  33. /**
  34. * The asynchronous operation has completed with an error.
  35. */
  36. public const REJECTED = 2;
  37. /**
  38. * The current state of this promise.
  39. *
  40. * @var int
  41. */
  42. public $state = self::PENDING;
  43. /**
  44. * Creates the promise.
  45. *
  46. * The passed argument is the executor. The executor is automatically
  47. * called with two arguments.
  48. *
  49. * Each are callbacks that map to $this->fulfill and $this->reject.
  50. * Using the executor is optional.
  51. */
  52. public function __construct(?callable $executor = null)
  53. {
  54. if ($executor) {
  55. $executor(
  56. [$this, 'fulfill'],
  57. [$this, 'reject']
  58. );
  59. }
  60. }
  61. /**
  62. * This method allows you to specify the callback that will be called after
  63. * the promise has been fulfilled or rejected.
  64. *
  65. * Both arguments are optional.
  66. *
  67. * This method returns a new promise, which can be used for chaining.
  68. * If either the onFulfilled or onRejected callback is called, you may
  69. * return a result from this callback.
  70. *
  71. * If the result of this callback is yet another promise, the result of
  72. * _that_ promise will be used to set the result of the returned promise.
  73. *
  74. * If either of the callbacks return any other value, the returned promise
  75. * is automatically fulfilled with that value.
  76. *
  77. * If either of the callbacks throw an exception, the returned promise will
  78. * be rejected and the exception will be passed back.
  79. */
  80. public function then(?callable $onFulfilled = null, ?callable $onRejected = null): Promise
  81. {
  82. // This new subPromise will be returned from this function, and will
  83. // be fulfilled with the result of the onFulfilled or onRejected event
  84. // handlers.
  85. $subPromise = new self();
  86. switch ($this->state) {
  87. case self::PENDING:
  88. // The operation is pending, so we keep a reference to the
  89. // event handlers so we can call them later.
  90. $this->subscribers[] = [$subPromise, $onFulfilled, $onRejected];
  91. break;
  92. case self::FULFILLED:
  93. // The async operation is already fulfilled, so we trigger the
  94. // onFulfilled callback asap.
  95. $this->invokeCallback($subPromise, $onFulfilled);
  96. break;
  97. case self::REJECTED:
  98. // The async operation failed, so we call the onRejected
  99. // callback asap.
  100. $this->invokeCallback($subPromise, $onRejected);
  101. break;
  102. }
  103. return $subPromise;
  104. }
  105. /**
  106. * Add a callback for when this promise is rejected.
  107. *
  108. * Its usage is identical to then(). However, the otherwise() function is
  109. * preferred.
  110. */
  111. public function otherwise(callable $onRejected): Promise
  112. {
  113. return $this->then(null, $onRejected);
  114. }
  115. /**
  116. * Marks this promise as fulfilled and sets its return value.
  117. */
  118. public function fulfill($value = null)
  119. {
  120. if (self::PENDING !== $this->state) {
  121. throw new PromiseAlreadyResolvedException('This promise is already resolved, and you\'re not allowed to resolve a promise more than once');
  122. }
  123. $this->state = self::FULFILLED;
  124. $this->value = $value;
  125. foreach ($this->subscribers as $subscriber) {
  126. $this->invokeCallback($subscriber[0], $subscriber[1]);
  127. }
  128. }
  129. /**
  130. * Marks this promise as rejected, and set its rejection reason.
  131. */
  132. public function reject(\Throwable $reason)
  133. {
  134. if (self::PENDING !== $this->state) {
  135. throw new PromiseAlreadyResolvedException('This promise is already resolved, and you\'re not allowed to resolve a promise more than once');
  136. }
  137. $this->state = self::REJECTED;
  138. $this->value = $reason;
  139. foreach ($this->subscribers as $subscriber) {
  140. $this->invokeCallback($subscriber[0], $subscriber[2]);
  141. }
  142. }
  143. /**
  144. * Stops execution until this promise is resolved.
  145. *
  146. * This method stops execution completely. If the promise is successful with
  147. * a value, this method will return this value. If the promise was
  148. * rejected, this method will throw an exception.
  149. *
  150. * This effectively turns the asynchronous operation into a synchronous
  151. * one. In PHP it might be useful to call this on the last promise in a
  152. * chain.
  153. *
  154. * @psalm-return TReturn
  155. */
  156. public function wait()
  157. {
  158. $hasEvents = true;
  159. while (self::PENDING === $this->state) {
  160. if (!$hasEvents) {
  161. throw new \LogicException('There were no more events in the loop. This promise will never be fulfilled.');
  162. }
  163. // As long as the promise is not fulfilled, we tell the event loop
  164. // to handle events, and to block.
  165. $hasEvents = Loop\tick(true);
  166. }
  167. if (self::FULFILLED === $this->state) {
  168. // If the state of this promise is fulfilled, we can return the value.
  169. return $this->value;
  170. } else {
  171. // If we got here, it means that the asynchronous operation
  172. // errored. Therefore we need to throw an exception.
  173. throw $this->value;
  174. }
  175. }
  176. /**
  177. * A list of subscribers. Subscribers are the callbacks that want us to let
  178. * them know if the callback was fulfilled or rejected.
  179. *
  180. * @var array
  181. */
  182. protected $subscribers = [];
  183. /**
  184. * The result of the promise.
  185. *
  186. * If the promise was fulfilled, this will be the result value. If the
  187. * promise was rejected, this property hold the rejection reason.
  188. */
  189. protected $value;
  190. /**
  191. * This method is used to call either an onFulfilled or onRejected callback.
  192. *
  193. * This method makes sure that the result of these callbacks are handled
  194. * correctly, and any chained promises are also correctly fulfilled or
  195. * rejected.
  196. */
  197. private function invokeCallback(Promise $subPromise, ?callable $callBack = null)
  198. {
  199. // We use 'nextTick' to ensure that the event handlers are always
  200. // triggered outside of the calling stack in which they were originally
  201. // passed to 'then'.
  202. //
  203. // This makes the order of execution more predictable.
  204. Loop\nextTick(function () use ($callBack, $subPromise) {
  205. if (is_callable($callBack)) {
  206. try {
  207. $result = $callBack($this->value);
  208. if ($result instanceof self) {
  209. // If the callback (onRejected or onFulfilled)
  210. // returned a promise, we only fulfill or reject the
  211. // chained promise once that promise has also been
  212. // resolved.
  213. $result->then([$subPromise, 'fulfill'], [$subPromise, 'reject']);
  214. } else {
  215. // If the callback returned any other value, we
  216. // immediately fulfill the chained promise.
  217. $subPromise->fulfill($result);
  218. }
  219. } catch (\Throwable $e) {
  220. // If the event handler threw an exception, we need to make sure that
  221. // the chained promise is rejected as well.
  222. $subPromise->reject($e);
  223. }
  224. } else {
  225. if (self::FULFILLED === $this->state) {
  226. $subPromise->fulfill($this->value);
  227. } else {
  228. $subPromise->reject($this->value);
  229. }
  230. }
  231. });
  232. }
  233. }