Promise.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. namespace GuzzleHttp\Promise;
  3. /**
  4. * Promises/A+ implementation that avoids recursion when possible.
  5. *
  6. * @link https://promisesaplus.com/
  7. */
  8. class Promise implements PromiseInterface
  9. {
  10. private $state = self::PENDING;
  11. private $result;
  12. private $cancelFn;
  13. private $waitFn;
  14. private $waitList;
  15. private $handlers = [];
  16. /**
  17. * @param callable $waitFn Fn that when invoked resolves the promise.
  18. * @param callable $cancelFn Fn that when invoked cancels the promise.
  19. */
  20. public function __construct(
  21. callable $waitFn = null,
  22. callable $cancelFn = null
  23. ) {
  24. $this->waitFn = $waitFn;
  25. $this->cancelFn = $cancelFn;
  26. }
  27. public function then(
  28. callable $onFulfilled = null,
  29. callable $onRejected = null
  30. ) {
  31. if ($this->state === self::PENDING) {
  32. $p = new Promise(null, [$this, 'cancel']);
  33. $this->handlers[] = [$p, $onFulfilled, $onRejected];
  34. $p->waitList = $this->waitList;
  35. $p->waitList[] = $this;
  36. return $p;
  37. }
  38. // Return a fulfilled promise and immediately invoke any callbacks.
  39. if ($this->state === self::FULFILLED) {
  40. return $onFulfilled
  41. ? promise_for($this->result)->then($onFulfilled)
  42. : promise_for($this->result);
  43. }
  44. // It's either cancelled or rejected, so return a rejected promise
  45. // and immediately invoke any callbacks.
  46. $rejection = rejection_for($this->result);
  47. return $onRejected ? $rejection->then(null, $onRejected) : $rejection;
  48. }
  49. public function otherwise(callable $onRejected)
  50. {
  51. return $this->then(null, $onRejected);
  52. }
  53. public function wait($unwrap = true)
  54. {
  55. $this->waitIfPending();
  56. $inner = $this->result instanceof PromiseInterface
  57. ? $this->result->wait($unwrap)
  58. : $this->result;
  59. if ($unwrap) {
  60. if ($this->result instanceof PromiseInterface
  61. || $this->state === self::FULFILLED
  62. ) {
  63. return $inner;
  64. } else {
  65. // It's rejected so "unwrap" and throw an exception.
  66. throw exception_for($inner);
  67. }
  68. }
  69. }
  70. public function getState()
  71. {
  72. return $this->state;
  73. }
  74. public function cancel()
  75. {
  76. if ($this->state !== self::PENDING) {
  77. return;
  78. }
  79. $this->waitFn = $this->waitList = null;
  80. if ($this->cancelFn) {
  81. $fn = $this->cancelFn;
  82. $this->cancelFn = null;
  83. try {
  84. $fn();
  85. } catch (\Throwable $e) {
  86. $this->reject($e);
  87. } catch (\Exception $e) {
  88. $this->reject($e);
  89. }
  90. }
  91. // Reject the promise only if it wasn't rejected in a then callback.
  92. if ($this->state === self::PENDING) {
  93. $this->reject(new CancellationException('Promise has been cancelled'));
  94. }
  95. }
  96. public function resolve($value)
  97. {
  98. $this->settle(self::FULFILLED, $value);
  99. }
  100. public function reject($reason)
  101. {
  102. $this->settle(self::REJECTED, $reason);
  103. }
  104. private function settle($state, $value)
  105. {
  106. if ($this->state !== self::PENDING) {
  107. // Ignore calls with the same resolution.
  108. if ($state === $this->state && $value === $this->result) {
  109. return;
  110. }
  111. throw $this->state === $state
  112. ? new \LogicException("The promise is already {$state}.")
  113. : new \LogicException("Cannot change a {$this->state} promise to {$state}");
  114. }
  115. if ($value === $this) {
  116. throw new \LogicException('Cannot fulfill or reject a promise with itself');
  117. }
  118. // Clear out the state of the promise but stash the handlers.
  119. $this->state = $state;
  120. $this->result = $value;
  121. $handlers = $this->handlers;
  122. $this->handlers = null;
  123. $this->waitList = $this->waitFn = null;
  124. $this->cancelFn = null;
  125. if (!$handlers) {
  126. return;
  127. }
  128. // If the value was not a settled promise or a thenable, then resolve
  129. // it in the task queue using the correct ID.
  130. if (!method_exists($value, 'then')) {
  131. $id = $state === self::FULFILLED ? 1 : 2;
  132. // It's a success, so resolve the handlers in the queue.
  133. queue()->add(static function () use ($id, $value, $handlers) {
  134. foreach ($handlers as $handler) {
  135. self::callHandler($id, $value, $handler);
  136. }
  137. });
  138. } elseif ($value instanceof Promise
  139. && $value->getState() === self::PENDING
  140. ) {
  141. // We can just merge our handlers onto the next promise.
  142. $value->handlers = array_merge($value->handlers, $handlers);
  143. } else {
  144. // Resolve the handlers when the forwarded promise is resolved.
  145. $value->then(
  146. static function ($value) use ($handlers) {
  147. foreach ($handlers as $handler) {
  148. self::callHandler(1, $value, $handler);
  149. }
  150. },
  151. static function ($reason) use ($handlers) {
  152. foreach ($handlers as $handler) {
  153. self::callHandler(2, $reason, $handler);
  154. }
  155. }
  156. );
  157. }
  158. }
  159. /**
  160. * Call a stack of handlers using a specific callback index and value.
  161. *
  162. * @param int $index 1 (resolve) or 2 (reject).
  163. * @param mixed $value Value to pass to the callback.
  164. * @param array $handler Array of handler data (promise and callbacks).
  165. *
  166. * @return array Returns the next group to resolve.
  167. */
  168. private static function callHandler($index, $value, array $handler)
  169. {
  170. /** @var PromiseInterface $promise */
  171. $promise = $handler[0];
  172. // The promise may have been cancelled or resolved before placing
  173. // this thunk in the queue.
  174. if ($promise->getState() !== self::PENDING) {
  175. return;
  176. }
  177. try {
  178. if (isset($handler[$index])) {
  179. $promise->resolve($handler[$index]($value));
  180. } elseif ($index === 1) {
  181. // Forward resolution values as-is.
  182. $promise->resolve($value);
  183. } else {
  184. // Forward rejections down the chain.
  185. $promise->reject($value);
  186. }
  187. } catch (\Throwable $reason) {
  188. $promise->reject($reason);
  189. } catch (\Exception $reason) {
  190. $promise->reject($reason);
  191. }
  192. }
  193. private function waitIfPending()
  194. {
  195. if ($this->state !== self::PENDING) {
  196. return;
  197. } elseif ($this->waitFn) {
  198. $this->invokeWaitFn();
  199. } elseif ($this->waitList) {
  200. $this->invokeWaitList();
  201. } else {
  202. // If there's not wait function, then reject the promise.
  203. $this->reject('Cannot wait on a promise that has '
  204. . 'no internal wait function. You must provide a wait '
  205. . 'function when constructing the promise to be able to '
  206. . 'wait on a promise.');
  207. }
  208. queue()->run();
  209. if ($this->state === self::PENDING) {
  210. $this->reject('Invoking the wait callback did not resolve the promise');
  211. }
  212. }
  213. private function invokeWaitFn()
  214. {
  215. try {
  216. $wfn = $this->waitFn;
  217. $this->waitFn = null;
  218. $wfn(true);
  219. } catch (\Exception $reason) {
  220. if ($this->state === self::PENDING) {
  221. // The promise has not been resolved yet, so reject the promise
  222. // with the exception.
  223. $this->reject($reason);
  224. } else {
  225. // The promise was already resolved, so there's a problem in
  226. // the application.
  227. throw $reason;
  228. }
  229. }
  230. }
  231. private function invokeWaitList()
  232. {
  233. $waitList = $this->waitList;
  234. $this->waitList = null;
  235. foreach ($waitList as $result) {
  236. while (true) {
  237. $result->waitIfPending();
  238. if ($result->result instanceof Promise) {
  239. $result = $result->result;
  240. } else {
  241. if ($result->result instanceof PromiseInterface) {
  242. $result->result->wait(false);
  243. }
  244. break;
  245. }
  246. }
  247. }
  248. }
  249. }