EachPromise.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. namespace GuzzleHttp\Promise;
  3. /**
  4. * Represents a promise that iterates over many promises and invokes
  5. * side-effect functions in the process.
  6. */
  7. class EachPromise implements PromisorInterface
  8. {
  9. private $pending = [];
  10. private $nextPendingIndex = 0;
  11. /** @var \Iterator|null */
  12. private $iterable;
  13. /** @var callable|int|null */
  14. private $concurrency;
  15. /** @var callable|null */
  16. private $onFulfilled;
  17. /** @var callable|null */
  18. private $onRejected;
  19. /** @var Promise|null */
  20. private $aggregate;
  21. /** @var bool|null */
  22. private $mutex;
  23. /**
  24. * Configuration hash can include the following key value pairs:
  25. *
  26. * - fulfilled: (callable) Invoked when a promise fulfills. The function
  27. * is invoked with three arguments: the fulfillment value, the index
  28. * position from the iterable list of the promise, and the aggregate
  29. * promise that manages all of the promises. The aggregate promise may
  30. * be resolved from within the callback to short-circuit the promise.
  31. * - rejected: (callable) Invoked when a promise is rejected. The
  32. * function is invoked with three arguments: the rejection reason, the
  33. * index position from the iterable list of the promise, and the
  34. * aggregate promise that manages all of the promises. The aggregate
  35. * promise may be resolved from within the callback to short-circuit
  36. * the promise.
  37. * - concurrency: (integer) Pass this configuration option to limit the
  38. * allowed number of outstanding concurrently executing promises,
  39. * creating a capped pool of promises. There is no limit by default.
  40. *
  41. * @param mixed $iterable Promises or values to iterate.
  42. * @param array $config Configuration options
  43. */
  44. public function __construct($iterable, array $config = [])
  45. {
  46. $this->iterable = Create::iterFor($iterable);
  47. if (isset($config['concurrency'])) {
  48. $this->concurrency = $config['concurrency'];
  49. }
  50. if (isset($config['fulfilled'])) {
  51. $this->onFulfilled = $config['fulfilled'];
  52. }
  53. if (isset($config['rejected'])) {
  54. $this->onRejected = $config['rejected'];
  55. }
  56. }
  57. /** @psalm-suppress InvalidNullableReturnType */
  58. public function promise()
  59. {
  60. if ($this->aggregate) {
  61. return $this->aggregate;
  62. }
  63. try {
  64. $this->createPromise();
  65. /** @psalm-assert Promise $this->aggregate */
  66. $this->iterable->rewind();
  67. $this->refillPending();
  68. } catch (\Throwable $e) {
  69. $this->aggregate->reject($e);
  70. } catch (\Exception $e) {
  71. $this->aggregate->reject($e);
  72. }
  73. /**
  74. * @psalm-suppress NullableReturnStatement
  75. * @phpstan-ignore-next-line
  76. */
  77. return $this->aggregate;
  78. }
  79. private function createPromise()
  80. {
  81. $this->mutex = false;
  82. $this->aggregate = new Promise(function () {
  83. if ($this->checkIfFinished()) {
  84. return;
  85. }
  86. reset($this->pending);
  87. // Consume a potentially fluctuating list of promises while
  88. // ensuring that indexes are maintained (precluding array_shift).
  89. while ($promise = current($this->pending)) {
  90. next($this->pending);
  91. $promise->wait();
  92. if (Is::settled($this->aggregate)) {
  93. return;
  94. }
  95. }
  96. });
  97. // Clear the references when the promise is resolved.
  98. $clearFn = function () {
  99. $this->iterable = $this->concurrency = $this->pending = null;
  100. $this->onFulfilled = $this->onRejected = null;
  101. $this->nextPendingIndex = 0;
  102. };
  103. $this->aggregate->then($clearFn, $clearFn);
  104. }
  105. private function refillPending()
  106. {
  107. if (!$this->concurrency) {
  108. // Add all pending promises.
  109. while ($this->addPending() && $this->advanceIterator());
  110. return;
  111. }
  112. // Add only up to N pending promises.
  113. $concurrency = is_callable($this->concurrency)
  114. ? call_user_func($this->concurrency, count($this->pending))
  115. : $this->concurrency;
  116. $concurrency = max($concurrency - count($this->pending), 0);
  117. // Concurrency may be set to 0 to disallow new promises.
  118. if (!$concurrency) {
  119. return;
  120. }
  121. // Add the first pending promise.
  122. $this->addPending();
  123. // Note this is special handling for concurrency=1 so that we do
  124. // not advance the iterator after adding the first promise. This
  125. // helps work around issues with generators that might not have the
  126. // next value to yield until promise callbacks are called.
  127. while (--$concurrency
  128. && $this->advanceIterator()
  129. && $this->addPending());
  130. }
  131. private function addPending()
  132. {
  133. if (!$this->iterable || !$this->iterable->valid()) {
  134. return false;
  135. }
  136. $promise = Create::promiseFor($this->iterable->current());
  137. $key = $this->iterable->key();
  138. // Iterable keys may not be unique, so we use a counter to
  139. // guarantee uniqueness
  140. $idx = $this->nextPendingIndex++;
  141. $this->pending[$idx] = $promise->then(
  142. function ($value) use ($idx, $key) {
  143. if ($this->onFulfilled) {
  144. call_user_func(
  145. $this->onFulfilled,
  146. $value,
  147. $key,
  148. $this->aggregate
  149. );
  150. }
  151. $this->step($idx);
  152. },
  153. function ($reason) use ($idx, $key) {
  154. if ($this->onRejected) {
  155. call_user_func(
  156. $this->onRejected,
  157. $reason,
  158. $key,
  159. $this->aggregate
  160. );
  161. }
  162. $this->step($idx);
  163. }
  164. );
  165. return true;
  166. }
  167. private function advanceIterator()
  168. {
  169. // Place a lock on the iterator so that we ensure to not recurse,
  170. // preventing fatal generator errors.
  171. if ($this->mutex) {
  172. return false;
  173. }
  174. $this->mutex = true;
  175. try {
  176. $this->iterable->next();
  177. $this->mutex = false;
  178. return true;
  179. } catch (\Throwable $e) {
  180. $this->aggregate->reject($e);
  181. $this->mutex = false;
  182. return false;
  183. } catch (\Exception $e) {
  184. $this->aggregate->reject($e);
  185. $this->mutex = false;
  186. return false;
  187. }
  188. }
  189. private function step($idx)
  190. {
  191. // If the promise was already resolved, then ignore this step.
  192. if (Is::settled($this->aggregate)) {
  193. return;
  194. }
  195. unset($this->pending[$idx]);
  196. // Only refill pending promises if we are not locked, preventing the
  197. // EachPromise to recursively invoke the provided iterator, which
  198. // cause a fatal error: "Cannot resume an already running generator"
  199. if ($this->advanceIterator() && !$this->checkIfFinished()) {
  200. // Add more pending promises if possible.
  201. $this->refillPending();
  202. }
  203. }
  204. private function checkIfFinished()
  205. {
  206. if (!$this->pending && !$this->iterable->valid()) {
  207. // Resolve the promise if there's nothing left to do.
  208. $this->aggregate->resolve(null);
  209. return true;
  210. }
  211. return false;
  212. }
  213. }