Coroutine.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Promise;
  4. use Generator;
  5. use Throwable;
  6. /**
  7. * Creates a promise that is resolved using a generator that yields values or
  8. * promises (somewhat similar to C#'s async keyword).
  9. *
  10. * When called, the Coroutine::of method will start an instance of the generator
  11. * and returns a promise that is fulfilled with its final yielded value.
  12. *
  13. * Control is returned back to the generator when the yielded promise settles.
  14. * This can lead to less verbose code when doing lots of sequential async calls
  15. * with minimal processing in between.
  16. *
  17. * use GuzzleHttp\Promise;
  18. *
  19. * function createPromise($value) {
  20. * return new Promise\FulfilledPromise($value);
  21. * }
  22. *
  23. * $promise = Promise\Coroutine::of(function () {
  24. * $value = (yield createPromise('a'));
  25. * try {
  26. * $value = (yield createPromise($value . 'b'));
  27. * } catch (\Throwable $e) {
  28. * // The promise was rejected.
  29. * }
  30. * yield $value . 'c';
  31. * });
  32. *
  33. * // Outputs "abc"
  34. * $promise->then(function ($v) { echo $v; });
  35. *
  36. * @param callable $generatorFn Generator function to wrap into a promise.
  37. *
  38. * @return Promise
  39. *
  40. * @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
  41. */
  42. final class Coroutine implements PromiseInterface
  43. {
  44. /**
  45. * @var PromiseInterface|null
  46. */
  47. private $currentPromise;
  48. /**
  49. * @var Generator
  50. */
  51. private $generator;
  52. /**
  53. * @var Promise
  54. */
  55. private $result;
  56. public function __construct(callable $generatorFn)
  57. {
  58. $this->generator = $generatorFn();
  59. $this->result = new Promise(function (): void {
  60. while (isset($this->currentPromise)) {
  61. $this->currentPromise->wait();
  62. }
  63. });
  64. try {
  65. $this->nextCoroutine($this->generator->current());
  66. } catch (Throwable $throwable) {
  67. $this->result->reject($throwable);
  68. }
  69. }
  70. /**
  71. * Create a new coroutine.
  72. */
  73. public static function of(callable $generatorFn): self
  74. {
  75. return new self($generatorFn);
  76. }
  77. public function then(
  78. callable $onFulfilled = null,
  79. callable $onRejected = null
  80. ): PromiseInterface {
  81. return $this->result->then($onFulfilled, $onRejected);
  82. }
  83. public function otherwise(callable $onRejected): PromiseInterface
  84. {
  85. return $this->result->otherwise($onRejected);
  86. }
  87. public function wait(bool $unwrap = true)
  88. {
  89. return $this->result->wait($unwrap);
  90. }
  91. public function getState(): string
  92. {
  93. return $this->result->getState();
  94. }
  95. public function resolve($value): void
  96. {
  97. $this->result->resolve($value);
  98. }
  99. public function reject($reason): void
  100. {
  101. $this->result->reject($reason);
  102. }
  103. public function cancel(): void
  104. {
  105. $this->currentPromise->cancel();
  106. $this->result->cancel();
  107. }
  108. private function nextCoroutine($yielded): void
  109. {
  110. $this->currentPromise = Create::promiseFor($yielded)
  111. ->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
  112. }
  113. /**
  114. * @internal
  115. */
  116. public function _handleSuccess($value): void
  117. {
  118. unset($this->currentPromise);
  119. try {
  120. $next = $this->generator->send($value);
  121. if ($this->generator->valid()) {
  122. $this->nextCoroutine($next);
  123. } else {
  124. $this->result->resolve($value);
  125. }
  126. } catch (Throwable $throwable) {
  127. $this->result->reject($throwable);
  128. }
  129. }
  130. /**
  131. * @internal
  132. */
  133. public function _handleFailure($reason): void
  134. {
  135. unset($this->currentPromise);
  136. try {
  137. $nextYield = $this->generator->throw(Create::exceptionFor($reason));
  138. // The throw was caught, so keep iterating on the coroutine
  139. $this->nextCoroutine($nextYield);
  140. } catch (Throwable $throwable) {
  141. $this->result->reject($throwable);
  142. }
  143. }
  144. }