vendor/guzzlehttp/promises/src/Utils.php

311 lines · 10000 bytes

  1<?php
  2
  3declare(strict_types=1);
  4
  5namespace GuzzleHttp\Promise;
  6
  7final class Utils
  8{
  9    /**
 10     * Get the global task queue used for promise resolution.
 11     *
 12     * This task queue MUST be run in an event loop in order for promises to be
 13     * settled asynchronously. It will be automatically run when synchronously
 14     * waiting on a promise.
 15     *
 16     * <code>
 17     * while ($eventLoop->isRunning()) {
 18     *     GuzzleHttp\Promise\Utils::queue()->run();
 19     * }
 20     * </code>
 21     *
 22     * @param TaskQueueInterface|null $assign Optionally specify a new queue instance.
 23     */
 24    public static function queue(?TaskQueueInterface $assign = null): TaskQueueInterface
 25    {
 26        static $queue;
 27
 28        if ($assign) {
 29            $queue = $assign;
 30        } elseif (!$queue) {
 31            $queue = new TaskQueue();
 32        }
 33
 34        return $queue;
 35    }
 36
 37    /**
 38     * Adds a function to run in the task queue when it is next `run()` and
 39     * returns a promise that is fulfilled or rejected with the result.
 40     *
 41     * @param callable $task Task function to run.
 42     */
 43    public static function task(callable $task): PromiseInterface
 44    {
 45        $queue = self::queue();
 46        $promise = new Promise([$queue, 'run']);
 47        $queue->add(function () use ($task, $promise): void {
 48            try {
 49                if (State::isPending($promise)) {
 50                    $promise->resolve($task());
 51                }
 52            } catch (\Throwable $e) {
 53                $promise->reject($e);
 54            }
 55        });
 56
 57        return $promise;
 58    }
 59
 60    /**
 61     * Synchronously waits on a promise to resolve and returns an inspection
 62     * state array.
 63     *
 64     * Returns a state associative array containing a "state" key mapping to a
 65     * valid promise state. If the state of the promise is "fulfilled", the
 66     * array will contain a "value" key mapping to the fulfilled value of the
 67     * promise. If the promise is rejected, the array will contain a "reason"
 68     * key mapping to the rejection reason of the promise.
 69     *
 70     * @param PromiseInterface $promise Promise or value.
 71     */
 72    public static function inspect(PromiseInterface $promise): array
 73    {
 74        try {
 75            return [
 76                'state' => PromiseInterface::FULFILLED,
 77                'value' => $promise->wait(),
 78            ];
 79        } catch (\Throwable $e) {
 80            if ($e instanceof AggregateException) {
 81                return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
 82            }
 83
 84            if ($e instanceof RejectionException) {
 85                return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()];
 86            }
 87
 88            return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
 89        }
 90    }
 91
 92    /**
 93     * Waits on all of the provided promises, but does not unwrap rejected
 94     * promises as thrown exception.
 95     *
 96     * Returns an array of inspection state arrays.
 97     *
 98     * @see inspect for the inspection state array format.
 99     *
100     * @param PromiseInterface[] $promises Traversable of promises to wait upon.
101     */
102    public static function inspectAll($promises): array
103    {
104        $promises = self::prepareIterable($promises, __FUNCTION__);
105
106        $results = [];
107        foreach ($promises as $key => $promise) {
108            $results[$key] = self::inspect($promise);
109        }
110
111        return $results;
112    }
113
114    /**
115     * Waits on all of the provided promises and returns the fulfilled values.
116     *
117     * Returns an array that contains the value of each promise (in the same
118     * order the promises were provided). An exception is thrown if any of the
119     * promises are rejected.
120     *
121     * @param iterable<PromiseInterface> $promises Iterable of PromiseInterface objects to wait on.
122     *
123     * @throws \Throwable on error
124     */
125    public static function unwrap($promises): array
126    {
127        $promises = self::prepareIterable($promises, __FUNCTION__);
128
129        $results = [];
130        foreach ($promises as $key => $promise) {
131            $results[$key] = $promise->wait();
132        }
133
134        return $results;
135    }
136
137    /**
138     * Given an array of promises, return a promise that is fulfilled when all
139     * the items in the array are fulfilled.
140     *
141     * The promise's fulfillment value is an array with fulfillment values at
142     * respective positions to the original array. If any promise in the array
143     * rejects, the returned promise is rejected with the rejection reason.
144     *
145     * @param mixed $promises  Promises or values.
146     * @param bool  $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
147     */
148    public static function all($promises, bool $recursive = false): PromiseInterface
149    {
150        $promises = self::prepareIterable($promises, __FUNCTION__);
151
152        $results = [];
153        $promise = Each::of(
154            $promises,
155            function ($value, $idx) use (&$results): void {
156                $results[$idx] = $value;
157            },
158            function ($reason, $idx, Promise $aggregate): void {
159                if (State::isPending($aggregate)) {
160                    $aggregate->reject($reason);
161                }
162            }
163        )->then(function () use (&$results) {
164            ksort($results);
165
166            return $results;
167        });
168
169        if (true === $recursive) {
170            $promise = $promise->then(function ($results) use ($recursive, &$promises) {
171                // A consumed generator cannot be traversed again, so a
172                // recursive pass has nothing further to observe.
173                if ($promises instanceof \Generator) {
174                    return $results;
175                }
176
177                foreach ($promises as $promise) {
178                    if (State::isPending($promise)) {
179                        return self::all($promises, $recursive);
180                    }
181                }
182
183                return $results;
184            });
185        }
186
187        return $promise;
188    }
189
190    /**
191     * Initiate a competitive race between multiple promises or values (values
192     * will become immediately fulfilled promises).
193     *
194     * When count amount of promises have been fulfilled, the returned promise
195     * is fulfilled with an array that contains the fulfillment values of the
196     * winners in order of resolution.
197     *
198     * This promise is rejected with a {@see AggregateException} if the number
199     * of fulfilled promises is less than the desired $count.
200     *
201     * @param int   $count    Total number of promises.
202     * @param mixed $promises Promises or values.
203     */
204    public static function some(int $count, $promises): PromiseInterface
205    {
206        $promises = self::prepareIterable($promises, __FUNCTION__);
207
208        $results = [];
209        $rejections = [];
210
211        return Each::of(
212            $promises,
213            function ($value, $idx, PromiseInterface $p) use (&$results, $count): void {
214                if (State::isSettled($p)) {
215                    return;
216                }
217                $results[$idx] = $value;
218                if (count($results) >= $count) {
219                    $p->resolve(null);
220                }
221            },
222            function ($reason) use (&$rejections): void {
223                $rejections[] = $reason;
224            }
225        )->then(
226            function () use (&$results, &$rejections, $count) {
227                if (count($results) !== $count) {
228                    throw new AggregateException(
229                        'Not enough promises to fulfill count',
230                        $rejections
231                    );
232                }
233                ksort($results);
234
235                return array_values($results);
236            }
237        );
238    }
239
240    /**
241     * Like some(), with 1 as count. However, if the promise fulfills, the
242     * fulfillment value is not an array of 1 but the value directly.
243     *
244     * @param mixed $promises Promises or values.
245     */
246    public static function any($promises): PromiseInterface
247    {
248        $promises = self::prepareIterable($promises, __FUNCTION__);
249
250        return self::some(1, $promises)->then(function ($values) {
251            return $values[0];
252        });
253    }
254
255    /**
256     * Returns a promise that is fulfilled when all of the provided promises have
257     * been fulfilled or rejected.
258     *
259     * The returned promise is fulfilled with an array of inspection state arrays.
260     *
261     * @see inspect for the inspection state array format.
262     *
263     * @param mixed $promises Promises or values.
264     */
265    public static function settle($promises): PromiseInterface
266    {
267        $promises = self::prepareIterable($promises, __FUNCTION__);
268
269        $results = [];
270
271        return Each::of(
272            $promises,
273            function ($value, $idx) use (&$results): void {
274                $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
275            },
276            function ($reason, $idx) use (&$results): void {
277                $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
278            }
279        )->then(function () use (&$results) {
280            ksort($results);
281
282            return $results;
283        });
284    }
285
286    private static function prepareIterable($promises, string $method): iterable
287    {
288        if (is_iterable($promises)) {
289            return $promises;
290        }
291
292        self::triggerNonIterableDeprecation($promises, $method);
293
294        return [$promises];
295    }
296
297    private static function triggerNonIterableDeprecation($promises, string $method): void
298    {
299        if (is_iterable($promises)) {
300            return;
301        }
302
303        \trigger_deprecation(
304            'guzzlehttp/promises',
305            '2.5',
306            'Passing a non-iterable to %s::%s() is deprecated; guzzlehttp/promises 3.0 will require an iterable.',
307            self::class,
308            $method
309        );
310    }
311}