Debian Codegraph @

vendor/react/async/src/functions.php

raw
1 <?php
2
3 namespace React\Async;
4
5 use React\EventLoop\Loop;
6 use React\EventLoop\TimerInterface;
7 use React\Promise\Deferred;
8 use React\Promise\Promise;
9 use React\Promise\PromiseInterface;
10 use function React\Promise\reject;
11 use function React\Promise\resolve;
12
13 /**
14 * Return an async function for a function that uses [`await()`](#await) internally.
15 *
16 * This function is specifically designed to complement the [`await()` function](#await).
17 * The [`await()` function](#await) can be considered *blocking* from the
18 * perspective of the calling code. You can avoid this blocking behavior by
19 * wrapping it in an `async()` function call. Everything inside this function
20 * will still be blocked, but everything outside this function can be executed
21 * asynchronously without blocking:
22 *
23 * ```php
24 * Loop::addTimer(0.5, React\Async\async(function () {
25 * echo 'a';
26 * React\Async\await(React\Promise\Timer\sleep(1.0));
27 * echo 'c';
28 * }));
29 *
30 * Loop::addTimer(1.0, function () {
31 * echo 'b';
32 * });
33 *
34 * // prints "a" at t=0.5s
35 * // prints "b" at t=1.0s
36 * // prints "c" at t=1.5s
37 * ```
38 *
39 * See also the [`await()` function](#await) for more details.
40 *
41 * Note that this function only works in tandem with the [`await()` function](#await).
42 * In particular, this function does not "magically" make any blocking function
43 * non-blocking:
44 *
45 * ```php
46 * Loop::addTimer(0.5, React\Async\async(function () {
47 * echo 'a';
48 * sleep(1); // broken: using PHP's blocking sleep() for demonstration purposes
49 * echo 'c';
50 * }));
51 *
52 * Loop::addTimer(1.0, function () {
53 * echo 'b';
54 * });
55 *
56 * // prints "a" at t=0.5s
57 * // prints "c" at t=1.5s: Correct timing, but wrong order
58 * // prints "b" at t=1.5s: Triggered too late because it was blocked
59 * ```
60 *
61 * As an alternative, you should always make sure to use this function in tandem
62 * with the [`await()` function](#await) and an async API returning a promise
63 * as shown in the previous example.
64 *
65 * The `async()` function is specifically designed for cases where it is used
66 * as a callback (such as an event loop timer, event listener, or promise
67 * callback). For this reason, it returns a new function wrapping the given
68 * `$function` instead of directly invoking it and returning its value.
69 *
70 * ```php
71 * use function React\Async\async;
72 *
73 * Loop::addTimer(1.0, async(function () { … }));
74 * $connection->on('close', async(function () { … }));
75 * $stream->on('data', async(function ($data) { … }));
76 * $promise->then(async(function (int $result) { … }));
77 * ```
78 *
79 * You can invoke this wrapping function to invoke the given `$function` with
80 * any arguments given as-is. The function will always return a Promise which
81 * will be fulfilled with whatever your `$function` returns. Likewise, it will
82 * return a promise that will be rejected if you throw an `Exception` or
83 * `Throwable` from your `$function`. This allows you to easily create
84 * Promise-based functions:
85 *
86 * ```php
87 * $promise = React\Async\async(function (): int {
88 * $browser = new React\Http\Browser();
89 * $urls = [
90 * 'https://example.com/alice',
91 * 'https://example.com/bob'
92 * ];
93 *
94 * $bytes = 0;
95 * foreach ($urls as $url) {
96 * $response = React\Async\await($browser->get($url));
97 * assert($response instanceof Psr\Http\Message\ResponseInterface);
98 * $bytes += $response->getBody()->getSize();
99 * }
100 * return $bytes;
101 * })();
102 *
103 * $promise->then(function (int $bytes) {
104 * echo 'Total size: ' . $bytes . PHP_EOL;
105 * }, function (Exception $e) {
106 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
107 * });
108 * ```
109 *
110 * The previous example uses [`await()`](#await) inside a loop to highlight how
111 * this vastly simplifies consuming asynchronous operations. At the same time,
112 * this naive example does not leverage concurrent execution, as it will
113 * essentially "await" between each operation. In order to take advantage of
114 * concurrent execution within the given `$function`, you can "await" multiple
115 * promises by using a single [`await()`](#await) together with Promise-based
116 * primitives like this:
117 *
118 * ```php
119 * $promise = React\Async\async(function (): int {
120 * $browser = new React\Http\Browser();
121 * $urls = [
122 * 'https://example.com/alice',
123 * 'https://example.com/bob'
124 * ];
125 *
126 * $promises = [];
127 * foreach ($urls as $url) {
128 * $promises[] = $browser->get($url);
129 * }
130 *
131 * try {
132 * $responses = React\Async\await(React\Promise\all($promises));
133 * } catch (Exception $e) {
134 * foreach ($promises as $promise) {
135 * $promise->cancel();
136 * }
137 * throw $e;
138 * }
139 *
140 * $bytes = 0;
141 * foreach ($responses as $response) {
142 * assert($response instanceof Psr\Http\Message\ResponseInterface);
143 * $bytes += $response->getBody()->getSize();
144 * }
145 * return $bytes;
146 * })();
147 *
148 * $promise->then(function (int $bytes) {
149 * echo 'Total size: ' . $bytes . PHP_EOL;
150 * }, function (Exception $e) {
151 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
152 * });
153 * ```
154 *
155 * The returned promise is implemented in such a way that it can be cancelled
156 * when it is still pending. Cancelling a pending promise will cancel any awaited
157 * promises inside that fiber or any nested fibers. As such, the following example
158 * will only output `ab` and cancel the pending [`delay()`](#delay).
159 * The [`await()`](#await) calls in this example would throw a `RuntimeException`
160 * from the cancelled [`delay()`](#delay) call that bubbles up through the fibers.
161 *
162 * ```php
163 * $promise = async(static function (): int {
164 * echo 'a';
165 * await(async(static function (): void {
166 * echo 'b';
167 * delay(2);
168 * echo 'c';
169 * })());
170 * echo 'd';
171 *
172 * return time();
173 * })();
174 *
175 * $promise->cancel();
176 * await($promise);
177 * ```
178 *
179 * @template T
180 * @template A1 (any number of function arguments, see https://github.com/phpstan/phpstan/issues/8214)
181 * @template A2
182 * @template A3
183 * @template A4
184 * @template A5
185 * @param callable(A1,A2,A3,A4,A5): (PromiseInterface<T>|T) $function
186 * @return callable(A1=,A2=,A3=,A4=,A5=): PromiseInterface<T>
187 * @since 4.0.0
188 * @see coroutine()
189 */
190 function async(callable $function): callable
191 {
192 return static function (mixed ...$args) use ($function): PromiseInterface {
193 $fiber = null;
194 /** @var PromiseInterface<T> $promise*/
195 $promise = new Promise(function (callable $resolve, callable $reject) use ($function, $args, &$fiber): void {
196 $fiber = new \Fiber(function () use ($resolve, $reject, $function, $args, &$fiber): void {
197 try {
198 $resolve($function(...$args));
199 } catch (\Throwable $exception) {
200 $reject($exception);
201 } finally {
202 assert($fiber instanceof \Fiber);
203 FiberMap::unsetPromise($fiber);
204 }
205 });
206
207 $fiber->start();
208 }, function () use (&$fiber): void {
209 assert($fiber instanceof \Fiber);
210 $promise = FiberMap::getPromise($fiber);
211 if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) {
212 $promise->cancel();
213 }
214 });
215
216 $lowLevelFiber = \Fiber::getCurrent();
217 if ($lowLevelFiber !== null) {
218 FiberMap::setPromise($lowLevelFiber, $promise);
219 }
220
221 return $promise;
222 };
223 }
224
225 /**
226 * Block waiting for the given `$promise` to be fulfilled.
227 *
228 * ```php
229 * $result = React\Async\await($promise);
230 * ```
231 *
232 * This function will only return after the given `$promise` has settled, i.e.
233 * either fulfilled or rejected. While the promise is pending, this function
234 * can be considered *blocking* from the perspective of the calling code.
235 * You can avoid this blocking behavior by wrapping it in an [`async()` function](#async)
236 * call. Everything inside this function will still be blocked, but everything
237 * outside this function can be executed asynchronously without blocking:
238 *
239 * ```php
240 * Loop::addTimer(0.5, React\Async\async(function () {
241 * echo 'a';
242 * React\Async\await(React\Promise\Timer\sleep(1.0));
243 * echo 'c';
244 * }));
245 *
246 * Loop::addTimer(1.0, function () {
247 * echo 'b';
248 * });
249 *
250 * // prints "a" at t=0.5s
251 * // prints "b" at t=1.0s
252 * // prints "c" at t=1.5s
253 * ```
254 *
255 * See also the [`async()` function](#async) for more details.
256 *
257 * Once the promise is fulfilled, this function will return whatever the promise
258 * resolved to.
259 *
260 * Once the promise is rejected, this will throw whatever the promise rejected
261 * with. If the promise did not reject with an `Exception` or `Throwable`, then
262 * this function will throw an `UnexpectedValueException` instead.
263 *
264 * ```php
265 * try {
266 * $result = React\Async\await($promise);
267 * // promise successfully fulfilled with $result
268 * echo 'Result: ' . $result;
269 * } catch (Throwable $e) {
270 * // promise rejected with $e
271 * echo 'Error: ' . $e->getMessage();
272 * }
273 * ```
274 *
275 * @template T
276 * @param PromiseInterface<T> $promise
277 * @return T returns whatever the promise resolves to
278 * @throws \Exception when the promise is rejected with an `Exception`
279 * @throws \Throwable when the promise is rejected with a `Throwable`
280 * @throws \UnexpectedValueException when the promise is rejected with an unexpected value (Promise API v1 or v2 only)
281 */
282 function await(PromiseInterface $promise): mixed
283 {
284 $fiber = null;
285 $resolved = false;
286 $rejected = false;
287
288 /** @var T $resolvedValue */
289 $resolvedValue = null;
290 $rejectedThrowable = null;
291 $lowLevelFiber = \Fiber::getCurrent();
292
293 $promise->then(
294 function (mixed $value) use (&$resolved, &$resolvedValue, &$fiber, $lowLevelFiber): void {
295 if ($lowLevelFiber !== null) {
296 FiberMap::unsetPromise($lowLevelFiber);
297 }
298
299 /** @var ?\Fiber<mixed,mixed,mixed,mixed> $fiber */
300 if ($fiber === null) {
301 $resolved = true;
302 /** @var T $resolvedValue */
303 $resolvedValue = $value;
304 return;
305 }
306
307 $fiber->resume($value);
308 },
309 function (mixed $throwable) use (&$rejected, &$rejectedThrowable, &$fiber, $lowLevelFiber): void {
310 if ($lowLevelFiber !== null) {
311 FiberMap::unsetPromise($lowLevelFiber);
312 }
313
314 if (!$throwable instanceof \Throwable) {
315 $throwable = new \UnexpectedValueException(
316 'Promise rejected with unexpected value of type ' . (is_object($throwable) ? get_class($throwable) : gettype($throwable)) /** @phpstan-ignore-line */
317 );
318
319 // avoid garbage references by replacing all closures in call stack.
320 // what a lovely piece of code!
321 $r = new \ReflectionProperty('Exception', 'trace');
322 $trace = $r->getValue($throwable);
323 assert(\is_array($trace));
324
325 // Exception trace arguments only available when zend.exception_ignore_args is not set
326 // @codeCoverageIgnoreStart
327 foreach ($trace as $ti => $one) {
328 if (isset($one['args'])) {
329 foreach ($one['args'] as $ai => $arg) {
330 if ($arg instanceof \Closure) {
331 $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')';
332 }
333 }
334 }
335 }
336 // @codeCoverageIgnoreEnd
337 $r->setValue($throwable, $trace);
338 }
339
340 if ($fiber === null) {
341 $rejected = true;
342 $rejectedThrowable = $throwable;
343 return;
344 }
345
346 $fiber->throw($throwable);
347 }
348 );
349
350 if ($resolved) {
351 return $resolvedValue;
352 }
353
354 if ($rejected) {
355 assert($rejectedThrowable instanceof \Throwable);
356 throw $rejectedThrowable;
357 }
358
359 if ($lowLevelFiber !== null) {
360 FiberMap::setPromise($lowLevelFiber, $promise);
361 }
362
363 $fiber = FiberFactory::create();
364
365 return $fiber->suspend();
366 }
367
368 /**
369 * Delay program execution for duration given in `$seconds`.
370 *
371 * ```php
372 * React\Async\delay($seconds);
373 * ```
374 *
375 * This function will only return after the given number of `$seconds` have
376 * elapsed. If there are no other events attached to this loop, it will behave
377 * similar to PHP's [`sleep()` function](https://www.php.net/manual/en/function.sleep.php).
378 *
379 * ```php
380 * echo 'a';
381 * React\Async\delay(1.0);
382 * echo 'b';
383 *
384 * // prints "a" at t=0.0s
385 * // prints "b" at t=1.0s
386 * ```
387 *
388 * Unlike PHP's [`sleep()` function](https://www.php.net/manual/en/function.sleep.php),
389 * this function may not necessarily halt execution of the entire process thread.
390 * Instead, it allows the event loop to run any other events attached to the
391 * same loop until the delay returns:
392 *
393 * ```php
394 * echo 'a';
395 * Loop::addTimer(1.0, function (): void {
396 * echo 'b';
397 * });
398 * React\Async\delay(3.0);
399 * echo 'c';
400 *
401 * // prints "a" at t=0.0s
402 * // prints "b" at t=1.0s
403 * // prints "c" at t=3.0s
404 * ```
405 *
406 * This behavior is especially useful if you want to delay the program execution
407 * of a particular routine, such as when building a simple polling or retry
408 * mechanism:
409 *
410 * ```php
411 * try {
412 * something();
413 * } catch (Throwable) {
414 * // in case of error, retry after a short delay
415 * React\Async\delay(1.0);
416 * something();
417 * }
418 * ```
419 *
420 * Because this function only returns after some time has passed, it can be
421 * considered *blocking* from the perspective of the calling code. You can avoid
422 * this blocking behavior by wrapping it in an [`async()` function](#async) call.
423 * Everything inside this function will still be blocked, but everything outside
424 * this function can be executed asynchronously without blocking:
425 *
426 * ```php
427 * Loop::addTimer(0.5, React\Async\async(function (): void {
428 * echo 'a';
429 * React\Async\delay(1.0);
430 * echo 'c';
431 * }));
432 *
433 * Loop::addTimer(1.0, function (): void {
434 * echo 'b';
435 * });
436 *
437 * // prints "a" at t=0.5s
438 * // prints "b" at t=1.0s
439 * // prints "c" at t=1.5s
440 * ```
441 *
442 * See also the [`async()` function](#async) for more details.
443 *
444 * Internally, the `$seconds` argument will be used as a timer for the loop so that
445 * it keeps running until this timer triggers. This implies that if you pass a
446 * really small (or negative) value, it will still start a timer and will thus
447 * trigger at the earliest possible time in the future.
448 *
449 * The function is implemented in such a way that it can be cancelled when it is
450 * running inside an [`async()` function](#async). Cancelling the resulting
451 * promise will clean up any pending timers and throw a `RuntimeException` from
452 * the pending delay which in turn would reject the resulting promise.
453 *
454 * ```php
455 * $promise = async(function (): void {
456 * echo 'a';
457 * delay(3.0);
458 * echo 'b';
459 * })();
460 *
461 * Loop::addTimer(2.0, function () use ($promise): void {
462 * $promise->cancel();
463 * });
464 *
465 * // prints "a" at t=0.0s
466 * // rejects $promise at t=2.0
467 * // never prints "b"
468 * ```
469 *
470 * @return void
471 * @throws \RuntimeException when the function is cancelled inside an `async()` function
472 * @see async()
473 * @uses await()
474 */
475 function delay(float $seconds): void
476 {
477 /** @var ?TimerInterface $timer */
478 $timer = null;
479
480 await(new Promise(function (callable $resolve) use ($seconds, &$timer): void {
481 $timer = Loop::addTimer($seconds, fn() => $resolve(null));
482 }, function () use (&$timer): void {
483 assert($timer instanceof TimerInterface);
484 Loop::cancelTimer($timer);
485 throw new \RuntimeException('Delay cancelled');
486 }));
487 }
488
489 /**
490 * Execute a Generator-based coroutine to "await" promises.
491 *
492 * ```php
493 * React\Async\coroutine(function () {
494 * $browser = new React\Http\Browser();
495 *
496 * try {
497 * $response = yield $browser->get('https://example.com/');
498 * assert($response instanceof Psr\Http\Message\ResponseInterface);
499 * echo $response->getBody();
500 * } catch (Exception $e) {
501 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
502 * }
503 * });
504 * ```
505 *
506 * Using Generator-based coroutines is an alternative to directly using the
507 * underlying promise APIs. For many use cases, this makes using promise-based
508 * APIs much simpler, as it resembles a synchronous code flow more closely.
509 * The above example performs the equivalent of directly using the promise APIs:
510 *
511 * ```php
512 * $browser = new React\Http\Browser();
513 *
514 * $browser->get('https://example.com/')->then(function (Psr\Http\Message\ResponseInterface $response) {
515 * echo $response->getBody();
516 * }, function (Exception $e) {
517 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
518 * });
519 * ```
520 *
521 * The `yield` keyword can be used to "await" a promise resolution. Internally,
522 * it will turn the entire given `$function` into a [`Generator`](https://www.php.net/manual/en/class.generator.php).
523 * This allows the execution to be interrupted and resumed at the same place
524 * when the promise is fulfilled. The `yield` statement returns whatever the
525 * promise is fulfilled with. If the promise is rejected, it will throw an
526 * `Exception` or `Throwable`.
527 *
528 * The `coroutine()` function will always return a Promise which will be
529 * fulfilled with whatever your `$function` returns. Likewise, it will return
530 * a promise that will be rejected if you throw an `Exception` or `Throwable`
531 * from your `$function`. This allows you to easily create Promise-based
532 * functions:
533 *
534 * ```php
535 * $promise = React\Async\coroutine(function () {
536 * $browser = new React\Http\Browser();
537 * $urls = [
538 * 'https://example.com/alice',
539 * 'https://example.com/bob'
540 * ];
541 *
542 * $bytes = 0;
543 * foreach ($urls as $url) {
544 * $response = yield $browser->get($url);
545 * assert($response instanceof Psr\Http\Message\ResponseInterface);
546 * $bytes += $response->getBody()->getSize();
547 * }
548 * return $bytes;
549 * });
550 *
551 * $promise->then(function (int $bytes) {
552 * echo 'Total size: ' . $bytes . PHP_EOL;
553 * }, function (Exception $e) {
554 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
555 * });
556 * ```
557 *
558 * The previous example uses a `yield` statement inside a loop to highlight how
559 * this vastly simplifies consuming asynchronous operations. At the same time,
560 * this naive example does not leverage concurrent execution, as it will
561 * essentially "await" between each operation. In order to take advantage of
562 * concurrent execution within the given `$function`, you can "await" multiple
563 * promises by using a single `yield` together with Promise-based primitives
564 * like this:
565 *
566 * ```php
567 * $promise = React\Async\coroutine(function () {
568 * $browser = new React\Http\Browser();
569 * $urls = [
570 * 'https://example.com/alice',
571 * 'https://example.com/bob'
572 * ];
573 *
574 * $promises = [];
575 * foreach ($urls as $url) {
576 * $promises[] = $browser->get($url);
577 * }
578 *
579 * try {
580 * $responses = yield React\Promise\all($promises);
581 * } catch (Exception $e) {
582 * foreach ($promises as $promise) {
583 * $promise->cancel();
584 * }
585 * throw $e;
586 * }
587 *
588 * $bytes = 0;
589 * foreach ($responses as $response) {
590 * assert($response instanceof Psr\Http\Message\ResponseInterface);
591 * $bytes += $response->getBody()->getSize();
592 * }
593 * return $bytes;
594 * });
595 *
596 * $promise->then(function (int $bytes) {
597 * echo 'Total size: ' . $bytes . PHP_EOL;
598 * }, function (Exception $e) {
599 * echo 'Error: ' . $e->getMessage() . PHP_EOL;
600 * });
601 * ```
602 *
603 * @template T
604 * @template TYield
605 * @template A1 (any number of function arguments, see https://github.com/phpstan/phpstan/issues/8214)
606 * @template A2
607 * @template A3
608 * @template A4
609 * @template A5
610 * @param callable(A1, A2, A3, A4, A5):(\Generator<mixed, PromiseInterface<TYield>, TYield, PromiseInterface<T>|T>|PromiseInterface<T>|T) $function
611 * @param mixed ...$args Optional list of additional arguments that will be passed to the given `$function` as is
612 * @return PromiseInterface<T>
613 * @since 3.0.0
614 */
615 function coroutine(callable $function, mixed ...$args): PromiseInterface
616 {
617 try {
618 $generator = $function(...$args);
619 } catch (\Throwable $e) {
620 return reject($e);
621 }
622
623 if (!$generator instanceof \Generator) {
624 return resolve($generator);
625 }
626
627 $promise = null;
628 /** @var Deferred<T> $deferred*/
629 $deferred = new Deferred(function () use (&$promise) {
630 /** @var ?PromiseInterface<T> $promise */
631 if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) {
632 $promise->cancel();
633 }
634 $promise = null;
635 });
636
637 /** @var callable $next */
638 $next = function () use ($deferred, $generator, &$next, &$promise) {
639 try {
640 if (!$generator->valid()) {
641 $next = null;
642 $deferred->resolve($generator->getReturn());
643 return;
644 }
645 } catch (\Throwable $e) {
646 $next = null;
647 $deferred->reject($e);
648 return;
649 }
650
651 $promise = $generator->current();
652 if (!$promise instanceof PromiseInterface) {
653 $next = null;
654 $deferred->reject(new \UnexpectedValueException(
655 'Expected coroutine to yield ' . PromiseInterface::class . ', but got ' . (is_object($promise) ? get_class($promise) : gettype($promise))
656 ));
657 return;
658 }
659
660 /** @var PromiseInterface<TYield> $promise */
661 assert($next instanceof \Closure);
662 $promise->then(function ($value) use ($generator, $next) {
663 $generator->send($value);
664 $next();
665 }, function (\Throwable $reason) use ($generator, $next) {
666 $generator->throw($reason);
667 $next();
668 })->then(null, function (\Throwable $reason) use ($deferred, &$next) {
669 $next = null;
670 $deferred->reject($reason);
671 });
672 };
673 $next();
674
675 return $deferred->promise();
676 }
677
678 /**
679 * @template T
680 * @param iterable<callable():(PromiseInterface<T>|T)> $tasks
681 * @return PromiseInterface<array<T>>
682 */
683 function parallel(iterable $tasks): PromiseInterface
684 {
685 /** @var array<int,PromiseInterface<T>> $pending */
686 $pending = [];
687 /** @var Deferred<array<T>> $deferred */
688 $deferred = new Deferred(function () use (&$pending) {
689 foreach ($pending as $promise) {
690 if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) {
691 $promise->cancel();
692 }
693 }
694 $pending = [];
695 });
696 $results = [];
697 $continue = true;
698
699 $taskErrback = function ($error) use (&$pending, $deferred, &$continue) {
700 $continue = false;
701 $deferred->reject($error);
702
703 foreach ($pending as $promise) {
704 if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) {
705 $promise->cancel();
706 }
707 }
708 $pending = [];
709 };
710
711 foreach ($tasks as $i => $task) {
712 $taskCallback = function ($result) use (&$results, &$pending, &$continue, $i, $deferred) {
713 $results[$i] = $result;
714 unset($pending[$i]);
715
716 if (!$pending && !$continue) {
717 $deferred->resolve($results);
718 }
719 };
720
721 $promise = \call_user_func($task);
722 assert($promise instanceof PromiseInterface);
723 $pending[$i] = $promise;
724
725 $promise->then($taskCallback, $taskErrback);
726
727 if (!$continue) {
728 break;
729 }
730 }
731
732 $continue = false;
733 if (!$pending) {
734 $deferred->resolve($results);
735 }
736
737 /** @var PromiseInterface<array<T>> Remove once defining `Deferred()` above is supported by PHPStan, see https://github.com/phpstan/phpstan/issues/11032 */
738 return $deferred->promise();
739 }
740
741 /**
742 * @template T
743 * @param iterable<callable():(PromiseInterface<T>|T)> $tasks
744 * @return PromiseInterface<array<T>>
745 */
746 function series(iterable $tasks): PromiseInterface
747 {
748 $pending = null;
749 /** @var Deferred<array<T>> $deferred */
750 $deferred = new Deferred(function () use (&$pending) {
751 /** @var ?PromiseInterface<T> $pending */
752 if ($pending instanceof PromiseInterface && \method_exists($pending, 'cancel')) {
753 $pending->cancel();
754 }
755 $pending = null;
756 });
757 $results = [];
758
759 if ($tasks instanceof \IteratorAggregate) {
760 $tasks = $tasks->getIterator();
761 assert($tasks instanceof \Iterator);
762 }
763
764 $taskCallback = function ($result) use (&$results, &$next) {
765 $results[] = $result;
766 /** @var \Closure $next */
767 $next();
768 };
769
770 $next = function () use (&$tasks, $taskCallback, $deferred, &$results, &$pending) {
771 if ($tasks instanceof \Iterator ? !$tasks->valid() : !$tasks) {
772 $deferred->resolve($results);
773 return;
774 }
775
776 if ($tasks instanceof \Iterator) {
777 $task = $tasks->current();
778 $tasks->next();
779 } else {
780 assert(\is_array($tasks));
781 $task = \array_shift($tasks);
782 }
783
784 assert(\is_callable($task));
785 $promise = \call_user_func($task);
786 assert($promise instanceof PromiseInterface);
787 $pending = $promise;
788
789 $promise->then($taskCallback, array($deferred, 'reject'));
790 };
791
792 $next();
793
794 /** @var PromiseInterface<array<T>> Remove once defining `Deferred()` above is supported by PHPStan, see https://github.com/phpstan/phpstan/issues/11032 */
795 return $deferred->promise();
796 }
797
798 /**
799 * @template T
800 * @param iterable<(callable():(PromiseInterface<T>|T))|(callable(mixed):(PromiseInterface<T>|T))> $tasks
801 * @return PromiseInterface<($tasks is non-empty-array|\Traversable ? T : null)>
802 */
803 function waterfall(iterable $tasks): PromiseInterface
804 {
805 $pending = null;
806 /** @var Deferred<T> $deferred*/
807 $deferred = new Deferred(function () use (&$pending) {
808 /** @var ?PromiseInterface<T> $pending */
809 if ($pending instanceof PromiseInterface && \method_exists($pending, 'cancel')) {
810 $pending->cancel();
811 }
812 $pending = null;
813 });
814
815 if ($tasks instanceof \IteratorAggregate) {
816 $tasks = $tasks->getIterator();
817 assert($tasks instanceof \Iterator);
818 }
819
820 /** @var callable $next */
821 $next = function ($value = null) use (&$tasks, &$next, $deferred, &$pending) {
822 if ($tasks instanceof \Iterator ? !$tasks->valid() : !$tasks) {
823 $deferred->resolve($value);
824 return;
825 }
826
827 if ($tasks instanceof \Iterator) {
828 $task = $tasks->current();
829 $tasks->next();
830 } else {
831 assert(\is_array($tasks));
832 $task = \array_shift($tasks);
833 }
834
835 assert(\is_callable($task));
836 $promise = \call_user_func_array($task, func_get_args());
837 assert($promise instanceof PromiseInterface);
838 $pending = $promise;
839
840 $promise->then($next, array($deferred, 'reject'));
841 };
842
843 $next();
844
845 return $deferred->promise();
846 }