Each.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. */
  21. public static function of(
  22. $iterable,
  23. callable $onFulfilled = null,
  24. callable $onRejected = null
  25. ): PromiseInterface {
  26. return (new EachPromise($iterable, [
  27. 'fulfilled' => $onFulfilled,
  28. 'rejected' => $onRejected,
  29. ]))->promise();
  30. }
  31. /**
  32. * Like of, but only allows a certain number of outstanding promises at any
  33. * given time.
  34. *
  35. * $concurrency may be an integer or a function that accepts the number of
  36. * pending promises and returns a numeric concurrency limit value to allow
  37. * for dynamic a concurrency size.
  38. *
  39. * @param mixed $iterable
  40. * @param int|callable $concurrency
  41. */
  42. public static function ofLimit(
  43. $iterable,
  44. $concurrency,
  45. callable $onFulfilled = null,
  46. callable $onRejected = null
  47. ): PromiseInterface {
  48. return (new EachPromise($iterable, [
  49. 'fulfilled' => $onFulfilled,
  50. 'rejected' => $onRejected,
  51. 'concurrency' => $concurrency,
  52. ]))->promise();
  53. }
  54. /**
  55. * Like limit, but ensures that no promise in the given $iterable argument
  56. * is rejected. If any promise is rejected, then the aggregate promise is
  57. * rejected with the encountered rejection.
  58. *
  59. * @param mixed $iterable
  60. * @param int|callable $concurrency
  61. */
  62. public static function ofLimitAll(
  63. $iterable,
  64. $concurrency,
  65. callable $onFulfilled = null
  66. ): PromiseInterface {
  67. return self::ofLimit(
  68. $iterable,
  69. $concurrency,
  70. $onFulfilled,
  71. function ($reason, $idx, PromiseInterface $aggregate): void {
  72. $aggregate->reject($reason);
  73. }
  74. );
  75. }
  76. }