Debian Codegraph @

vendor/react/promise-timer/src/functions.php

raw
1 <?php
2
3 namespace React\Promise\Timer;
4
5 use React\EventLoop\Loop;
6 use React\EventLoop\LoopInterface;
7 use React\Promise\Promise;
8 use React\Promise\PromiseInterface;
9
10 /**
11 * Cancel operations that take *too long*.
12 *
13 * You need to pass in an input `$promise` that represents a pending operation
14 * and timeout parameters. It returns a new promise with the following
15 * resolution behavior:
16 *
17 * - If the input `$promise` resolves before `$time` seconds, resolve the
18 * resulting promise with its fulfillment value.
19 *
20 * - If the input `$promise` rejects before `$time` seconds, reject the
21 * resulting promise with its rejection value.
22 *
23 * - If the input `$promise` does not settle before `$time` seconds, *cancel*
24 * the operation and reject the resulting promise with a [`TimeoutException`](#timeoutexception).
25 *
26 * Internally, the given `$time` value will be used to start a timer that will
27 * *cancel* the pending operation once it triggers. This implies that if you
28 * pass a really small (or negative) value, it will still start a timer and will
29 * thus trigger at the earliest possible time in the future.
30 *
31 * If the input `$promise` is already settled, then the resulting promise will
32 * resolve or reject immediately without starting a timer at all.
33 *
34 * This function takes an optional `LoopInterface|null $loop` parameter that can be used to
35 * pass the event loop instance to use. You can use a `null` value here in order to
36 * use the [default loop](https://github.com/reactphp/event-loop#loop). This value
37 * SHOULD NOT be given unless you're sure you want to explicitly use a given event
38 * loop instance.
39 *
40 * A common use case for handling only resolved values looks like this:
41 *
42 * ```php
43 * $promise = accessSomeRemoteResource();
44 * React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
45 * // the operation finished within 10.0 seconds
46 * });
47 * ```
48 *
49 * A more complete example could look like this:
50 *
51 * ```php
52 * $promise = accessSomeRemoteResource();
53 * React\Promise\Timer\timeout($promise, 10.0)->then(
54 * function ($value) {
55 * // the operation finished within 10.0 seconds
56 * },
57 * function ($error) {
58 * if ($error instanceof React\Promise\Timer\TimeoutException) {
59 * // the operation has failed due to a timeout
60 * } else {
61 * // the input operation has failed due to some other error
62 * }
63 * }
64 * );
65 * ```
66 *
67 * Or if you're using [react/promise v3](https://github.com/reactphp/promise):
68 *
69 * ```php
70 * React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
71 * // the operation finished within 10.0 seconds
72 * })->catch(function (React\Promise\Timer\TimeoutException $error) {
73 * // the operation has failed due to a timeout
74 * })->catch(function (Throwable $error) {
75 * // the input operation has failed due to some other error
76 * });
77 * ```
78 *
79 * As discussed above, the [`timeout()`](#timeout) function will take care of
80 * the underlying operation if it takes *too long*. In this case, you can be
81 * sure the resulting promise will always be rejected with a
82 * [`TimeoutException`](#timeoutexception). On top of this, the function will
83 * try to *cancel* the underlying operation. Responsibility for this
84 * cancellation logic is left up to the underlying operation.
85 *
86 * - A common use case involves cleaning up any resources like open network
87 * sockets or file handles or terminating external processes or timers.
88 *
89 * - If the given input `$promise` does not support cancellation, then this is a
90 * NO-OP. This means that while the resulting promise will still be rejected,
91 * the underlying input `$promise` may still be pending and can hence continue
92 * consuming resources
93 *
94 * On top of this, the returned promise is implemented in such a way that it can
95 * be cancelled when it is still pending. Cancelling a pending promise will
96 * cancel the underlying operation. As discussed above, responsibility for this
97 * cancellation logic is left up to the underlying operation.
98 *
99 * ```php
100 * $promise = accessSomeRemoteResource();
101 * $timeout = React\Promise\Timer\timeout($promise, 10.0);
102 *
103 * $timeout->cancel();
104 * ```
105 *
106 * For more details on the promise cancellation, please refer to the
107 * [Promise documentation](https://github.com/reactphp/promise#cancellablepromiseinterface).
108 *
109 * If you want to wait for multiple promises to resolve, you can use the normal
110 * promise primitives like this:
111 *
112 * ```php
113 * $promises = array(
114 * accessSomeRemoteResource(),
115 * accessSomeRemoteResource(),
116 * accessSomeRemoteResource()
117 * );
118 *
119 * $promise = React\Promise\all($promises);
120 *
121 * React\Promise\Timer\timeout($promise, 10)->then(function ($values) {
122 * // *all* promises resolved
123 * });
124 * ```
125 *
126 * The applies to all promise collection primitives alike, i.e. `all()`,
127 * `race()`, `any()`, `some()` etc.
128 *
129 * For more details on the promise primitives, please refer to the
130 * [Promise documentation](https://github.com/reactphp/promise#functions).
131 *
132 * @template T
133 * @param PromiseInterface<T> $promise
134 * @param float $time
135 * @param ?LoopInterface $loop
136 * @return PromiseInterface<T>
137 */
138 function timeout(PromiseInterface $promise, $time, $loop = null)
139 {
140 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
141 throw new \InvalidArgumentException('Argument #3 ($loop) expected null|React\EventLoop\LoopInterface');
142 }
143
144 // cancelling this promise will only try to cancel the input promise,
145 // thus leaving responsibility to the input promise.
146 $canceller = null;
147 if (\method_exists($promise, 'cancel')) {
148 // pass promise by reference to clean reference after cancellation handler
149 // has been invoked once in order to avoid garbage references in call stack.
150 $canceller = function () use (&$promise) {
151 $promise->cancel();
152 $promise = null;
153 };
154 }
155
156 if ($loop === null) {
157 $loop = Loop::get();
158 }
159
160 return new Promise(function ($resolve, $reject) use ($loop, $time, $promise) {
161 $timer = null;
162 $promise = $promise->then(function ($v) use (&$timer, $loop, $resolve) {
163 if ($timer) {
164 $loop->cancelTimer($timer);
165 }
166 $timer = false;
167 $resolve($v);
168 }, function ($v) use (&$timer, $loop, $reject) {
169 if ($timer) {
170 $loop->cancelTimer($timer);
171 }
172 $timer = false;
173 $reject($v);
174 });
175
176 // promise already resolved => no need to start timer
177 if ($timer === false) {
178 return;
179 }
180
181 // start timeout timer which will cancel the input promise
182 $timer = $loop->addTimer($time, function () use ($time, &$promise, $reject) {
183 $reject(new TimeoutException($time, 'Timed out after ' . $time . ' seconds'));
184
185 // try to invoke cancellation handler of input promise and then clean
186 // reference in order to avoid garbage references in call stack.
187 if (\method_exists($promise, 'cancel')) {
188 $promise->cancel();
189 }
190 $promise = null;
191 });
192 }, $canceller);
193 }
194
195 /**
196 * Create a new promise that resolves in `$time` seconds.
197 *
198 * ```php
199 * React\Promise\Timer\sleep(1.5)->then(function () {
200 * echo 'Thanks for waiting!' . PHP_EOL;
201 * });
202 * ```
203 *
204 * Internally, the given `$time` value will be used to start a timer that will
205 * resolve the promise once it triggers. This implies that if you pass a really
206 * small (or negative) value, it will still start a timer and will thus trigger
207 * at the earliest possible time in the future.
208 *
209 * This function takes an optional `LoopInterface|null $loop` parameter that can be used to
210 * pass the event loop instance to use. You can use a `null` value here in order to
211 * use the [default loop](https://github.com/reactphp/event-loop#loop). This value
212 * SHOULD NOT be given unless you're sure you want to explicitly use a given event
213 * loop instance.
214 *
215 * The returned promise is implemented in such a way that it can be cancelled
216 * when it is still pending. Cancelling a pending promise will reject its value
217 * with a `RuntimeException` and clean up any pending timers.
218 *
219 * ```php
220 * $timer = React\Promise\Timer\sleep(2.0);
221 *
222 * $timer->cancel();
223 * ```
224 *
225 * @param float $time
226 * @param ?LoopInterface $loop
227 * @return PromiseInterface<void>
228 */
229 function sleep($time, $loop = null)
230 {
231 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
232 throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface');
233 }
234
235 if ($loop === null) {
236 $loop = Loop::get();
237 }
238
239 $timer = null;
240 return new Promise(function ($resolve) use ($loop, $time, &$timer) {
241 // resolve the promise when the timer fires in $time seconds
242 $timer = $loop->addTimer($time, function () use ($resolve) {
243 $resolve(null);
244 });
245 }, function () use (&$timer, $loop) {
246 // cancelling this promise will cancel the timer, clean the reference
247 // in order to avoid garbage references in call stack and then reject.
248 $loop->cancelTimer($timer);
249 $timer = null;
250
251 throw new \RuntimeException('Timer cancelled');
252 });
253 }
254
255 /**
256 * [Deprecated] Create a new promise that resolves in `$time` seconds with the `$time` as the fulfillment value.
257 *
258 * ```php
259 * React\Promise\Timer\resolve(1.5)->then(function ($time) {
260 * echo 'Thanks for waiting ' . $time . ' seconds' . PHP_EOL;
261 * });
262 * ```
263 *
264 * Internally, the given `$time` value will be used to start a timer that will
265 * resolve the promise once it triggers. This implies that if you pass a really
266 * small (or negative) value, it will still start a timer and will thus trigger
267 * at the earliest possible time in the future.
268 *
269 * This function takes an optional `LoopInterface|null $loop` parameter that can be used to
270 * pass the event loop instance to use. You can use a `null` value here in order to
271 * use the [default loop](https://github.com/reactphp/event-loop#loop). This value
272 * SHOULD NOT be given unless you're sure you want to explicitly use a given event
273 * loop instance.
274 *
275 * The returned promise is implemented in such a way that it can be cancelled
276 * when it is still pending. Cancelling a pending promise will reject its value
277 * with a `RuntimeException` and clean up any pending timers.
278 *
279 * ```php
280 * $timer = React\Promise\Timer\resolve(2.0);
281 *
282 * $timer->cancel();
283 * ```
284 *
285 * @param float $time
286 * @param ?LoopInterface $loop
287 * @return PromiseInterface<float>
288 * @deprecated 1.8.0 See `sleep()` instead
289 * @see sleep()
290 */
291 function resolve($time, $loop = null)
292 {
293 return sleep($time, $loop)->then(function() use ($time) {
294 return $time;
295 });
296 }
297
298 /**
299 * [Deprecated] Create a new promise which rejects in `$time` seconds with a `TimeoutException`.
300 *
301 * ```php
302 * React\Promise\Timer\reject(2.0)->then(null, function (React\Promise\Timer\TimeoutException $e) {
303 * echo 'Rejected after ' . $e->getTimeout() . ' seconds ' . PHP_EOL;
304 * });
305 * ```
306 *
307 * Internally, the given `$time` value will be used to start a timer that will
308 * reject the promise once it triggers. This implies that if you pass a really
309 * small (or negative) value, it will still start a timer and will thus trigger
310 * at the earliest possible time in the future.
311 *
312 * This function takes an optional `LoopInterface|null $loop` parameter that can be used to
313 * pass the event loop instance to use. You can use a `null` value here in order to
314 * use the [default loop](https://github.com/reactphp/event-loop#loop). This value
315 * SHOULD NOT be given unless you're sure you want to explicitly use a given event
316 * loop instance.
317 *
318 * The returned promise is implemented in such a way that it can be cancelled
319 * when it is still pending. Cancelling a pending promise will reject its value
320 * with a `RuntimeException` and clean up any pending timers.
321 *
322 * ```php
323 * $timer = React\Promise\Timer\reject(2.0);
324 *
325 * $timer->cancel();
326 * ```
327 *
328 * @param float $time
329 * @param ?LoopInterface $loop
330 * @return PromiseInterface<never>
331 * @deprecated 1.8.0 See `sleep()` instead
332 * @see sleep()
333 */
334 function reject($time, $loop = null)
335 {
336 return sleep($time, $loop)->then(function () use ($time) {
337 throw new TimeoutException($time, 'Timer expired after ' . $time . ' seconds');
338 });
339 }