Debian Codegraph @

vendor/clue/block-react/src/functions.php

raw
1 <?php
2
3 namespace Clue\React\Block;
4
5 use React\EventLoop\LoopInterface;
6 use React\Promise\PromiseInterface;
7 use React\Promise\CancellablePromiseInterface;
8 use UnderflowException;
9 use Exception;
10 use React\Promise;
11 use React\Promise\Timer;
12 use React\Promise\Timer\TimeoutException;
13
14 /**
15 * Wait/sleep for `$time` seconds.
16 *
17 * ```php
18 * Block\sleep(1.5, $loop);
19 * ```
20 *
21 * This function will only return after the given `$time` has elapsed. In the
22 * meantime, the event loop will run any other events attached to the same loop
23 * until the timer fires. If there are no other events attached to this loop,
24 * it will behave similar to the built-in [`sleep()`](https://www.php.net/manual/en/function.sleep.php).
25 *
26 * Internally, the `$time` argument will be used as a timer for the loop so that
27 * it keeps running until this timer triggers. This implies that if you pass a
28 * really small (or negative) value, it will still start a timer and will thus
29 * trigger at the earliest possible time in the future.
30 *
31 * @param float $time
32 * @param LoopInterface $loop
33 * @return void
34 */
35 function sleep($time, LoopInterface $loop)
36 {
37 await(Timer\resolve($time, $loop), $loop);
38 }
39
40 /**
41 * Block waiting for the given `$promise` to be fulfilled.
42 *
43 * ```php
44 * $result = Block\await($promise, $loop, $timeout);
45 * ```
46 *
47 * This function will only return after the given `$promise` has settled, i.e.
48 * either fulfilled or rejected. In the meantime, the event loop will run any
49 * events attached to the same loop until the promise settles.
50 *
51 * Once the promise is fulfilled, this function will return whatever the promise
52 * resolved to.
53 *
54 * Once the promise is rejected, this will throw whatever the promise rejected
55 * with. If the promise did not reject with an `Exception`, then this function
56 * will throw an `UnexpectedValueException` instead.
57 *
58 * ```php
59 * try {
60 * $result = Block\await($promise, $loop);
61 * // promise successfully fulfilled with $result
62 * echo 'Result: ' . $result;
63 * } catch (Exception $exception) {
64 * // promise rejected with $exception
65 * echo 'ERROR: ' . $exception->getMessage();
66 * }
67 * ```
68 *
69 * See also the [examples](../examples/).
70 *
71 * If no `$timeout` argument is given and the promise stays pending, then this
72 * will potentially wait/block forever until the promise is settled.
73 *
74 * If a `$timeout` argument is given and the promise is still pending once the
75 * timeout triggers, this will `cancel()` the promise and throw a `TimeoutException`.
76 * This implies that if you pass a really small (or negative) value, it will still
77 * start a timer and will thus trigger at the earliest possible time in the future.
78 *
79 * @param PromiseInterface $promise
80 * @param LoopInterface $loop
81 * @param null|float $timeout (optional) maximum timeout in seconds or null=wait forever
82 * @return mixed returns whatever the promise resolves to
83 * @throws Exception when the promise is rejected
84 * @throws TimeoutException if the $timeout is given and triggers
85 */
86 function await(PromiseInterface $promise, LoopInterface $loop, $timeout = null)
87 {
88 $wait = true;
89 $resolved = null;
90 $exception = null;
91 $rejected = false;
92
93 if ($timeout !== null) {
94 $promise = Timer\timeout($promise, $timeout, $loop);
95 }
96
97 $promise->then(
98 function ($c) use (&$resolved, &$wait, $loop) {
99 $resolved = $c;
100 $wait = false;
101 $loop->stop();
102 },
103 function ($error) use (&$exception, &$rejected, &$wait, $loop) {
104 $exception = $error;
105 $rejected = true;
106 $wait = false;
107 $loop->stop();
108 }
109 );
110
111 // Explicitly overwrite argument with null value. This ensure that this
112 // argument does not show up in the stack trace in PHP 7+ only.
113 $promise = null;
114
115 while ($wait) {
116 $loop->run();
117 }
118
119 if ($rejected) {
120 if (!$exception instanceof \Exception) {
121 $exception = new \UnexpectedValueException(
122 'Promise rejected with unexpected value of type ' . (is_object($exception) ? get_class($exception) : gettype($exception)),
123 0,
124 $exception instanceof \Throwable ? $exception : null
125 );
126 }
127
128 throw $exception;
129 }
130
131 return $resolved;
132 }
133
134 /**
135 * Wait for ANY of the given promises to be fulfilled.
136 *
137 * ```php
138 * $promises = array(
139 * $promise1,
140 * $promise2
141 * );
142 *
143 * $firstResult = Block\awaitAny($promises, $loop, $timeout);
144 *
145 * echo 'First result: ' . $firstResult;
146 * ```
147 *
148 * See also the [examples](../examples/).
149 *
150 * This function will only return after ANY of the given `$promises` has been
151 * fulfilled or will throw when ALL of them have been rejected. In the meantime,
152 * the event loop will run any events attached to the same loop.
153 *
154 * Once ANY promise is fulfilled, this function will return whatever this
155 * promise resolved to and will try to `cancel()` all remaining promises.
156 *
157 * Once ALL promises reject, this function will fail and throw an `UnderflowException`.
158 * Likewise, this will throw if an empty array of `$promises` is passed.
159 *
160 * If no `$timeout` argument is given and ALL promises stay pending, then this
161 * will potentially wait/block forever until the promise is fulfilled.
162 *
163 * If a `$timeout` argument is given and ANY promises are still pending once
164 * the timeout triggers, this will `cancel()` all pending promises and throw a
165 * `TimeoutException`. This implies that if you pass a really small (or negative)
166 * value, it will still start a timer and will thus trigger at the earliest
167 * possible time in the future.
168 *
169 * @param array $promises
170 * @param LoopInterface $loop
171 * @param null|float $timeout (optional) maximum timeout in seconds or null=wait forever
172 * @return mixed returns whatever the first promise resolves to
173 * @throws Exception if ALL promises are rejected
174 * @throws TimeoutException if the $timeout is given and triggers
175 */
176 function awaitAny(array $promises, LoopInterface $loop, $timeout = null)
177 {
178 // Explicitly overwrite argument with null value. This ensure that this
179 // argument does not show up in the stack trace in PHP 7+ only.
180 $all = $promises;
181 $promises = null;
182
183 try {
184 // Promise\any() does not cope with an empty input array, so reject this here
185 if (!$all) {
186 throw new UnderflowException('Empty input array');
187 }
188
189 $ret = await(Promise\any($all)->then(null, function () {
190 // rejects with an array of rejection reasons => reject with Exception instead
191 throw new Exception('All promises rejected');
192 }), $loop, $timeout);
193 } catch (TimeoutException $e) {
194 // the timeout fired
195 // => try to cancel all promises (rejected ones will be ignored anyway)
196 _cancelAllPromises($all);
197
198 throw $e;
199 } catch (Exception $e) {
200 // if the above throws, then ALL promises are already rejected
201 // => try to cancel all promises (rejected ones will be ignored anyway)
202 _cancelAllPromises($all);
203
204 throw new UnderflowException('No promise could resolve', 0, $e);
205 }
206
207 // if we reach this, then ANY of the given promises resolved
208 // => try to cancel all promises (settled ones will be ignored anyway)
209 _cancelAllPromises($all);
210
211 return $ret;
212 }
213
214 /**
215 * Wait for ALL of the given promises to be fulfilled.
216 *
217 * ```php
218 * $promises = array(
219 * $promise1,
220 * $promise2
221 * );
222 *
223 * $allResults = Block\awaitAll($promises, $loop, $timeout);
224 *
225 * echo 'First promise resolved with: ' . $allResults[0];
226 * ```
227 *
228 * See also the [examples](../examples/).
229 *
230 * This function will only return after ALL of the given `$promises` have been
231 * fulfilled or will throw when ANY of them have been rejected. In the meantime,
232 * the event loop will run any events attached to the same loop.
233 *
234 * Once ALL promises are fulfilled, this will return an array with whatever
235 * each promise resolves to. Array keys will be left intact, i.e. they can
236 * be used to correlate the return array to the promises passed.
237 *
238 * Once ANY promise rejects, this will try to `cancel()` all remaining promises
239 * and throw an `Exception`. If the promise did not reject with an `Exception`,
240 * then this function will throw an `UnexpectedValueException` instead.
241 *
242 * If no `$timeout` argument is given and ANY promises stay pending, then this
243 * will potentially wait/block forever until the promise is fulfilled.
244 *
245 * If a `$timeout` argument is given and ANY promises are still pending once
246 * the timeout triggers, this will `cancel()` all pending promises and throw a
247 * `TimeoutException`. This implies that if you pass a really small (or negative)
248 * value, it will still start a timer and will thus trigger at the earliest
249 * possible time in the future.
250 *
251 * @param array $promises
252 * @param LoopInterface $loop
253 * @param null|float $timeout (optional) maximum timeout in seconds or null=wait forever
254 * @return array returns an array with whatever each promise resolves to
255 * @throws Exception when ANY promise is rejected
256 * @throws TimeoutException if the $timeout is given and triggers
257 */
258 function awaitAll(array $promises, LoopInterface $loop, $timeout = null)
259 {
260 // Explicitly overwrite argument with null value. This ensure that this
261 // argument does not show up in the stack trace in PHP 7+ only.
262 $all = $promises;
263 $promises = null;
264
265 try {
266 return await(Promise\all($all), $loop, $timeout);
267 } catch (Exception $e) {
268 // ANY of the given promises rejected or the timeout fired
269 // => try to cancel all promises (rejected ones will be ignored anyway)
270 _cancelAllPromises($all);
271
272 throw $e;
273 }
274 }
275
276 /**
277 * internal helper function used to iterate over an array of Promise instances and cancel() each
278 *
279 * @internal
280 * @param array $promises
281 * @return void
282 */
283 function _cancelAllPromises(array $promises)
284 {
285 foreach ($promises as $promise) {
286 if ($promise instanceof CancellablePromiseInterface) {
287 $promise->cancel();
288 }
289 }
290 }