Each.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Promise;
  4. final class Each
  5. {
  6. /**
  7. * Given an iterator that yields promises or values, returns a promise that
  8. * is fulfilled with a null value when the iterator has been consumed or
  9. * the aggregate promise has been fulfilled or rejected.
  10. *
  11. * $onFulfilled is a function that accepts the fulfilled value, iterator
  12. * index, and the aggregate promise. The callback can invoke any necessary
  13. * side effects and choose to resolve or reject the aggregate if needed.
  14. *
  15. * $onRejected is a function that accepts the rejection reason, iterator
  16. * index, and the aggregate promise. The callback can invoke any necessary
  17. * side effects and choose to resolve or reject the aggregate if needed.
  18. *
  19. * @param mixed $iterable Iterator or array to iterate over.
  20. * @param callable $onFulfilled
  21. * @param callable $onRejected
  22. */
  23. public static function of(
  24. $iterable,
  25. callable $onFulfilled = null,
  26. callable $onRejected = null
  27. ): PromiseInterface {
  28. return (new EachPromise($iterable, [
  29. 'fulfilled' => $onFulfilled,
  30. 'rejected' => $onRejected,
  31. ]))->promise();
  32. }
  33. /**
  34. * Like of, but only allows a certain number of outstanding promises at any
  35. * given time.
  36. *
  37. * $concurrency may be an integer or a function that accepts the number of
  38. * pending promises and returns a numeric concurrency limit value to allow
  39. * for dynamic a concurrency size.
  40. *
  41. * @param mixed $iterable
  42. * @param int|callable $concurrency
  43. * @param callable $onFulfilled
  44. * @param callable $onRejected
  45. */
  46. public static function ofLimit(
  47. $iterable,
  48. $concurrency,
  49. callable $onFulfilled = null,
  50. callable $onRejected = null
  51. ): PromiseInterface {
  52. return (new EachPromise($iterable, [
  53. 'fulfilled' => $onFulfilled,
  54. 'rejected' => $onRejected,
  55. 'concurrency' => $concurrency,
  56. ]))->promise();
  57. }
  58. /**
  59. * Like limit, but ensures that no promise in the given $iterable argument
  60. * is rejected. If any promise is rejected, then the aggregate promise is
  61. * rejected with the encountered rejection.
  62. *
  63. * @param mixed $iterable
  64. * @param int|callable $concurrency
  65. * @param callable $onFulfilled
  66. */
  67. public static function ofLimitAll(
  68. $iterable,
  69. $concurrency,
  70. callable $onFulfilled = null
  71. ): PromiseInterface {
  72. return self::ofLimit(
  73. $iterable,
  74. $concurrency,
  75. $onFulfilled,
  76. function ($reason, $idx, PromiseInterface $aggregate): void {
  77. $aggregate->reject($reason);
  78. }
  79. );
  80. }
  81. }