1
0
mirror of https://github.com/danog/amp.git synced 2024-11-26 20:15:00 +01:00
amp/lib/functions.php

702 lines
22 KiB
PHP
Raw Permalink Normal View History

<?php
2016-08-16 06:46:26 +02:00
2018-06-18 20:00:01 +02:00
namespace Amp
{
use React\Promise\PromiseInterface as ReactPromise;
/**
* Returns a new function that wraps $callback in a promise/coroutine-aware function that automatically runs
2017-05-03 15:21:49 +02:00
* Generators as coroutines. The returned function always returns a promise when invoked. Errors have to be handled
* by the callback caller or they will go unnoticed.
*
2017-05-03 15:21:49 +02:00
* Use this function to create a coroutine-aware callable for a promise-aware callback caller.
*
2017-05-03 15:21:49 +02:00
* @param callable(mixed ...$args): mixed $callback
*
2017-05-03 15:21:49 +02:00
* @return callable(mixed ...$args): \Amp\Promise
*
2017-05-03 15:21:49 +02:00
* @see asyncCoroutine()
*/
2018-06-18 20:00:01 +02:00
function coroutine(callable $callback): callable
{
2017-05-03 15:21:49 +02:00
return function (...$args) use ($callback): Promise {
return call($callback, ...$args);
};
}
/**
* Returns a new function that wraps $callback in a promise/coroutine-aware function that automatically runs
2017-05-03 15:21:49 +02:00
* Generators as coroutines. The returned function always returns void when invoked. Errors are forwarded to the
* loop's error handler using `Amp\Promise\rethrow()`.
*
2017-05-03 15:21:49 +02:00
* Use this function to create a coroutine-aware callable for a non-promise-aware callback caller.
*
2017-05-03 15:21:49 +02:00
* @param callable(...$args): \Generator|\Amp\Promise|mixed $callback
*
2017-05-03 15:21:49 +02:00
* @return callable(...$args): void
*
2017-05-03 15:21:49 +02:00
* @see coroutine()
*/
2018-06-18 20:00:01 +02:00
function asyncCoroutine(callable $callback): callable
{
2017-05-03 15:21:49 +02:00
return function (...$args) use ($callback) {
Promise\rethrow(call($callback, ...$args));
};
}
/**
* Calls the given function, always returning a promise. If the function returns a Generator, it will be run as a
* coroutine. If the function throws, a failed promise will be returned.
*
* @param callable(mixed ...$args):\Generator|mixed $callback
* @param mixed ...$args Arguments to pass to the function.
*
* @return \Amp\Promise
*/
2018-06-18 20:00:01 +02:00
function call(callable $callback, ...$args): Promise
{
try {
$result = $callback(...$args);
} catch (\Throwable $exception) {
return new Failure($exception);
}
2016-05-21 19:19:48 +02:00
if ($result instanceof \Generator) {
return new Coroutine($result);
}
2016-12-11 16:17:51 +01:00
2017-03-14 17:56:36 +01:00
if ($result instanceof Promise) {
return $result;
2016-05-21 19:19:48 +02:00
}
2016-05-21 16:44:52 +02:00
2017-03-14 17:56:36 +01:00
if ($result instanceof ReactPromise) {
return Promise\adapt($result);
2017-03-14 17:56:36 +01:00
}
return new Success($result);
2017-02-22 22:52:30 +01:00
}
2017-05-03 15:21:49 +02:00
/**
* Calls the given function. If the function returns a Generator, it will be run as a coroutine. If the function
* throws or returns a failing promise, the failure is forwarded to the loop error handler.
*
* @param callable(mixed ...$args):\Generator|mixed $callback
* @param mixed ...$args
2017-05-03 15:21:49 +02:00
*
* @throws \TypeError
*/
2018-06-18 20:00:01 +02:00
function asyncCall(callable $callback, ...$args)
{
2017-05-03 15:21:49 +02:00
Promise\rethrow(call($callback, ...$args));
}
2017-02-22 22:52:30 +01:00
}
2018-06-18 20:00:01 +02:00
namespace Amp\Promise
{
use Amp\Deferred;
2018-11-25 17:56:42 +01:00
use Amp\Failure;
2017-04-23 14:39:19 +02:00
use Amp\Loop;
use Amp\MultiReasonException;
use Amp\Promise;
use Amp\Success;
use Amp\TimeoutException;
use React\Promise\PromiseInterface as ReactPromise;
2018-11-25 17:56:42 +01:00
use function Amp\call;
use function Amp\Internal\createTypeError;
2016-05-21 16:44:52 +02:00
/**
2017-04-23 15:47:52 +02:00
* Registers a callback that will forward the failure reason to the event loop's error handler if the promise fails.
*
2017-04-23 15:47:52 +02:00
* Use this function if you neither return the promise nor handle a possible error yourself to prevent errors from
* going entirely unnoticed.
*
* @param \Amp\Promise|\React\Promise\PromiseInterface $promise Promise to register the handler on.
*
* @throws \TypeError If $promise is not an instance of \Amp\Promise or \React\Promise\PromiseInterface.
*/
2018-06-18 20:00:01 +02:00
function rethrow($promise)
{
if (!$promise instanceof Promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} else {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
}
}
$promise->onResolve(function ($exception) {
if ($exception) {
throw $exception;
}
2016-05-21 19:19:48 +02:00
});
2016-05-21 16:44:52 +02:00
}
/**
* Runs the event loop until the promise is resolved. Should not be called within a running event loop.
*
2017-04-23 15:47:52 +02:00
* Use this function only in synchronous contexts to wait for an asynchronous operation. Use coroutines and yield to
* await promise resolution in a fully asynchronous application instead.
*
* @param \Amp\Promise|\React\Promise\PromiseInterface $promise Promise to wait for.
*
* @return mixed Promise success value.
*
* @throws \TypeError If $promise is not an instance of \Amp\Promise or \React\Promise\PromiseInterface.
2017-04-23 15:47:52 +02:00
* @throws \Error If the event loop stopped without the $promise being resolved.
* @throws \Throwable Promise failure reason.
*/
2018-06-18 20:00:01 +02:00
function wait($promise)
{
if (!$promise instanceof Promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} else {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
}
}
$resolved = false;
try {
Loop::run(function () use (&$resolved, &$value, &$exception, $promise) {
$promise->onResolve(function ($e, $v) use (&$resolved, &$value, &$exception) {
Loop::stop();
$resolved = true;
$exception = $e;
$value = $v;
});
});
} catch (\Throwable $throwable) {
throw new \Error("Loop exceptionally stopped without resolving the promise", 0, $throwable);
}
2016-05-21 19:19:48 +02:00
if (!$resolved) {
throw new \Error("Loop stopped without resolving the promise");
2016-05-21 19:19:48 +02:00
}
2016-05-21 16:44:52 +02:00
if ($exception) {
throw $exception;
2016-05-21 19:19:48 +02:00
}
2016-05-21 16:44:52 +02:00
return $value;
}
2016-05-21 16:44:52 +02:00
/**
2017-04-23 15:47:52 +02:00
* Creates an artificial timeout for any `Promise`.
*
* If the timeout expires before the promise is resolved, the returned promise fails with an instance of
2017-04-23 15:47:52 +02:00
* `Amp\TimeoutException`.
*
2017-04-23 15:47:52 +02:00
* @param \Amp\Promise|\React\Promise\PromiseInterface $promise Promise to which the timeout is applied.
2018-06-18 20:00:01 +02:00
* @param int $timeout Timeout in milliseconds.
2016-05-21 16:44:52 +02:00
*
* @return \Amp\Promise
*
* @throws \TypeError If $promise is not an instance of \Amp\Promise or \React\Promise\PromiseInterface.
2016-05-21 16:44:52 +02:00
*/
2018-06-18 20:00:01 +02:00
function timeout($promise, int $timeout): Promise
{
if (!$promise instanceof Promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} else {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
}
}
$deferred = new Deferred;
2016-05-21 16:44:52 +02:00
$watcher = Loop::delay($timeout, function () use (&$deferred) {
2017-04-07 18:47:44 +02:00
$temp = $deferred; // prevent double resolve
$deferred = null;
2017-04-07 18:47:44 +02:00
$temp->fail(new TimeoutException);
2016-05-21 16:44:52 +02:00
});
Loop::unreference($watcher);
2016-05-21 16:44:52 +02:00
$promise->onResolve(function () use (&$deferred, $promise, $watcher) {
if ($deferred !== null) {
Loop::cancel($watcher);
$deferred->resolve($promise);
}
});
2016-05-21 16:44:52 +02:00
2017-04-07 19:19:37 +02:00
return $deferred->promise();
2016-05-21 16:44:52 +02:00
}
2018-11-25 17:56:42 +01:00
/**
* Creates an artificial timeout for any `Promise`.
*
* If the promise is resolved before the timeout expires, the result is returned
*
* If the timeout expires before the promise is resolved, a default value is returned
*
* @param \Amp\Promise|\React\Promise\PromiseInterface $promise Promise to which the timeout is applied.
* @param int $timeout Timeout in milliseconds.
* @param mixed $default
*
* @return \Amp\Promise
*
* @throws \TypeError If $promise is not an instance of \Amp\Promise or \React\Promise\PromiseInterface.
*/
function timeoutWithDefault($promise, int $timeout, $default = null): Promise
{
$promise = timeout($promise, $timeout);
return call(function () use ($promise, $default) {
try {
return yield $promise;
} catch (TimeoutException $exception) {
return $default;
}
});
}
/**
* Adapts any object with a done(callable $onFulfilled, callable $onRejected) or then(callable $onFulfilled,
* callable $onRejected) method to a promise usable by components depending on placeholders implementing
* \AsyncInterop\Promise.
*
* @param object $promise Object with a done() or then() method.
*
* @return \Amp\Promise Promise resolved by the $thenable object.
*
* @throws \Error If the provided object does not have a then() method.
*/
2018-06-18 20:00:01 +02:00
function adapt($promise): Promise
{
$deferred = new Deferred;
2016-05-21 16:44:52 +02:00
if (\method_exists($promise, 'done')) {
$promise->done([$deferred, 'resolve'], [$deferred, 'fail']);
} elseif (\method_exists($promise, 'then')) {
$promise->then([$deferred, 'resolve'], [$deferred, 'fail']);
} else {
throw new \Error("Object must have a 'then' or 'done' method");
}
return $deferred->promise();
}
2016-05-21 16:44:52 +02:00
/**
* Returns a promise that is resolved when all promises are resolved. The returned promise will not fail.
* Returned promise succeeds with a two-item array delineating successful and failed promise results,
* with keys identical and corresponding to the original given array.
*
* This function is the same as some() with the notable exception that it will never fail even
* if all promises in the array resolve unsuccessfully.
*
2018-11-26 19:36:46 +01:00
* @param \Amp\Promise[]|\React\Promise\PromiseInterface[] $promises
*
* @return \Amp\Promise
*
* @throws \Error If a non-Promise is in the array.
*/
2018-06-18 20:00:01 +02:00
function any(array $promises): Promise
{
return some($promises, 0);
2016-05-21 16:44:52 +02:00
}
/**
* Returns a promise that succeeds when all promises succeed, and fails if any promise fails. Returned
* promise succeeds with an array of values used to succeed each contained promise, with keys corresponding to
* the array of promises.
*
2018-11-26 19:36:46 +01:00
* @param \Amp\Promise[]|\React\Promise\PromiseInterface[] $promises Array of only promises.
*
* @return \Amp\Promise
*
* @throws \Error If a non-Promise is in the array.
*/
2018-06-18 20:00:01 +02:00
function all(array $promises): Promise
{
if (empty($promises)) {
return new Success([]);
}
2016-05-21 16:44:52 +02:00
$deferred = new Deferred;
$result = $deferred->promise();
2016-05-21 16:44:52 +02:00
$pending = \count($promises);
$values = [];
foreach ($promises as $key => $promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} elseif (!$promise instanceof Promise) {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
2016-05-24 04:32:41 +02:00
}
$values[$key] = null; // add entry to array to preserve order
2017-04-07 19:19:37 +02:00
$promise->onResolve(function ($exception, $value) use (&$deferred, &$values, &$pending, $key) {
2017-04-07 18:47:44 +02:00
if ($pending === 0) {
return;
}
2016-05-21 16:44:52 +02:00
if ($exception) {
2017-04-07 18:47:44 +02:00
$pending = 0;
$deferred->fail($exception);
2017-04-07 19:19:37 +02:00
$deferred = null;
return;
}
2016-05-21 16:44:52 +02:00
$values[$key] = $value;
if (0 === --$pending) {
$deferred->resolve($values);
}
});
}
2016-05-21 19:19:48 +02:00
return $result;
2016-05-21 16:44:52 +02:00
}
/**
* Returns a promise that succeeds when the first promise succeeds, and fails only if all promises fail.
*
2018-11-26 19:36:46 +01:00
* @param \Amp\Promise[]|\React\Promise\PromiseInterface[] $promises Array of only promises.
*
* @return \Amp\Promise
*
* @throws \Error If the array is empty or a non-Promise is in the array.
*/
2018-06-18 20:00:01 +02:00
function first(array $promises): Promise
{
if (empty($promises)) {
throw new \Error("No promises provided");
}
2016-05-21 16:44:52 +02:00
$deferred = new Deferred;
$result = $deferred->promise();
2016-05-21 19:19:48 +02:00
$pending = \count($promises);
$exceptions = [];
foreach ($promises as $key => $promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} elseif (!$promise instanceof Promise) {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
2016-07-31 07:31:04 +02:00
}
$exceptions[$key] = null; // add entry to array to preserve order
2017-12-05 08:48:36 +01:00
$promise->onResolve(function ($error, $value) use (&$deferred, &$exceptions, &$pending, $key) {
2017-04-07 18:47:44 +02:00
if ($pending === 0) {
2016-07-31 07:31:04 +02:00
return;
2016-05-21 16:44:52 +02:00
}
2017-04-13 18:49:32 +02:00
if (!$error) {
2017-04-07 18:47:44 +02:00
$pending = 0;
$deferred->resolve($value);
2017-04-07 19:19:37 +02:00
$deferred = null;
return;
}
2017-04-13 18:49:32 +02:00
$exceptions[$key] = $error;
if (0 === --$pending) {
$deferred->fail(new MultiReasonException($exceptions));
}
});
}
return $result;
2016-05-21 16:44:52 +02:00
}
/**
* Resolves with a two-item array delineating successful and failed Promise results.
*
* The returned promise will only fail if the given number of required promises fail.
*
2018-11-26 19:36:46 +01:00
* @param \Amp\Promise[]|\React\Promise\PromiseInterface[] $promises Array of only promises.
2018-06-18 20:00:01 +02:00
* @param int $required Number of promises that must succeed for the returned promise to succeed.
*
* @return \Amp\Promise
*
* @throws \Error If a non-Promise is in the array.
*/
2018-06-18 20:00:01 +02:00
function some(array $promises, int $required = 1): Promise
{
2017-03-27 18:42:11 +02:00
if ($required < 0) {
throw new \Error("Number of promises required must be non-negative");
}
$pending = \count($promises);
2016-05-21 16:44:52 +02:00
2017-03-27 18:42:11 +02:00
if ($required > $pending) {
throw new \Error("Too few promises provided");
}
if (empty($promises)) {
return new Success([[], []]);
}
$deferred = new Deferred;
$result = $deferred->promise();
$values = [];
$exceptions = [];
foreach ($promises as $key => $promise) {
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} elseif (!$promise instanceof Promise) {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
}
$values[$key] = $exceptions[$key] = null; // add entry to arrays to preserve order
$promise->onResolve(function ($exception, $value) use (
2018-06-18 20:00:01 +02:00
&$values,
&$exceptions,
&$pending,
$key,
$required,
$deferred
) {
if ($exception) {
$exceptions[$key] = $exception;
unset($values[$key]);
} else {
$values[$key] = $value;
unset($exceptions[$key]);
}
2016-07-19 06:29:19 +02:00
if (0 === --$pending) {
if (\count($values) < $required) {
$deferred->fail(new MultiReasonException($exceptions));
2017-04-07 18:47:44 +02:00
} else {
$deferred->resolve([$exceptions, $values]);
}
}
});
}
return $result;
}
2018-11-26 19:36:46 +01:00
/**
* Wraps a promise into another promise, altering the exception or result.
*
* @param \Amp\Promise|\React\Promise\PromiseInterface $promise
* @param callable $callback
* @return Promise
*/
function wrap($promise, callable $callback): Promise
{
if ($promise instanceof ReactPromise) {
$promise = adapt($promise);
} elseif (!$promise instanceof Promise) {
throw createTypeError([Promise::class, ReactPromise::class], $promise);
}
$deferred = new Deferred();
$promise->onResolve(function (\Throwable $exception = null, $result) use ($deferred, $callback) {
try {
$result = $callback($exception, $result);
} catch (\Throwable $exception) {
$deferred->fail($exception);
return;
}
$deferred->resolve($result);
});
return $deferred->promise();
}
2016-07-19 06:23:25 +02:00
}
2018-06-18 20:00:01 +02:00
namespace Amp\Iterator
{
use Amp\Delayed;
use Amp\Emitter;
2017-04-27 17:51:06 +02:00
use Amp\Iterator;
use Amp\Producer;
use Amp\Promise;
2018-10-05 21:01:57 +02:00
use function Amp\call;
2017-04-26 20:06:41 +02:00
use function Amp\coroutine;
use function Amp\Internal\createTypeError;
/**
2017-04-27 17:51:06 +02:00
* Creates an iterator from the given iterable, emitting the each value. The iterable may contain promises. If any
* promise fails, the iterator will fail with the same reason.
*
* @param array|\Traversable $iterable Elements to emit.
2018-06-18 20:00:01 +02:00
* @param int $delay Delay between element emissions in milliseconds.
*
2017-04-27 17:51:06 +02:00
* @return \Amp\Iterator
*
* @throws \TypeError If the argument is not an array or instance of \Traversable.
*/
2018-06-18 20:00:01 +02:00
function fromIterable(/* iterable */
$iterable,
int $delay = 0
): Iterator {
if (!$iterable instanceof \Traversable && !\is_array($iterable)) {
throw createTypeError(["array", "Traversable"], $iterable);
2016-05-24 18:47:14 +02:00
}
return new Producer(function (callable $emit) use ($iterable, $delay) {
foreach ($iterable as $value) {
if ($delay) {
yield new Delayed($delay);
}
yield $emit($value);
}
});
2016-05-24 18:47:14 +02:00
}
2016-12-11 16:17:51 +01:00
/**
2017-04-27 17:51:06 +02:00
* @param \Amp\Iterator $iterator
* @param callable (mixed $value): mixed $onEmit
*
2017-04-27 17:51:06 +02:00
* @return \Amp\Iterator
*/
2018-06-18 20:00:01 +02:00
function map(Iterator $iterator, callable $onEmit): Iterator
{
2017-04-27 17:51:06 +02:00
return new Producer(function (callable $emit) use ($iterator, $onEmit) {
while (yield $iterator->advance()) {
yield $emit($onEmit($iterator->getCurrent()));
}
});
}
/**
2017-04-27 17:51:06 +02:00
* @param \Amp\Iterator $iterator
* @param callable (mixed $value): bool $filter
*
2017-04-27 17:51:06 +02:00
* @return \Amp\Iterator
*/
2018-06-18 20:00:01 +02:00
function filter(Iterator $iterator, callable $filter): Iterator
{
2017-04-27 17:51:06 +02:00
return new Producer(function (callable $emit) use ($iterator, $filter) {
while (yield $iterator->advance()) {
if ($filter($iterator->getCurrent())) {
yield $emit($iterator->getCurrent());
}
}
});
}
/**
2017-04-27 17:51:06 +02:00
* Creates an iterator that emits values emitted from any iterator in the array of iterators.
*
2017-04-27 17:51:06 +02:00
* @param \Amp\Iterator[] $iterators
*
2017-04-27 17:51:06 +02:00
* @return \Amp\Iterator
*/
2018-06-18 20:00:01 +02:00
function merge(array $iterators): Iterator
{
$emitter = new Emitter;
2017-05-01 07:29:23 +02:00
$result = $emitter->iterate();
2017-04-27 17:51:06 +02:00
$coroutine = coroutine(function (Iterator $iterator) use (&$emitter) {
while ((yield $iterator->advance()) && $emitter !== null) {
yield $emitter->emit($iterator->getCurrent());
2017-04-26 20:06:41 +02:00
}
});
$coroutines = [];
2017-04-27 17:51:06 +02:00
foreach ($iterators as $iterator) {
if (!$iterator instanceof Iterator) {
throw createTypeError([Iterator::class], $iterator);
}
2017-04-27 17:51:06 +02:00
$coroutines[] = $coroutine($iterator);
2016-05-24 18:47:14 +02:00
}
2016-12-11 16:17:51 +01:00
2017-04-26 20:06:41 +02:00
Promise\all($coroutines)->onResolve(function ($exception) use (&$emitter) {
if ($exception) {
$emitter->fail($exception);
$emitter = null;
} else {
2017-04-26 20:14:10 +02:00
$emitter->complete();
}
});
return $result;
2016-08-01 18:10:59 +02:00
}
2016-12-11 16:17:51 +01:00
/**
2017-04-27 17:51:06 +02:00
* Concatenates the given iterators into a single iterator, emitting values from a single iterator at a time. The
* prior iterator must complete before values are emitted from any subsequent iterators. Iterators are concatenated
* in the order given (iteration order of the array).
*
2017-04-27 17:51:06 +02:00
* @param array $iterators
*
2017-04-27 17:51:06 +02:00
* @return \Amp\Iterator
*/
2018-06-18 20:00:01 +02:00
function concat(array $iterators): Iterator
{
2017-04-27 17:51:06 +02:00
foreach ($iterators as $iterator) {
if (!$iterator instanceof Iterator) {
throw createTypeError([Iterator::class], $iterator);
}
}
2016-12-11 16:17:51 +01:00
$emitter = new Emitter;
$previous = [];
$promise = Promise\all($previous);
2017-04-27 17:51:06 +02:00
$coroutine = coroutine(function (Iterator $iterator, callable $emit) {
while (yield $iterator->advance()) {
yield $emit($iterator->getCurrent());
2017-04-26 20:06:41 +02:00
}
});
2017-04-27 17:51:06 +02:00
foreach ($iterators as $iterator) {
2017-04-26 20:06:41 +02:00
$emit = coroutine(function ($value) use ($emitter, $promise) {
static $pending = true, $failed = false;
if ($failed) {
return;
}
if ($pending) {
try {
yield $promise;
$pending = false;
} catch (\Throwable $exception) {
$failed = true;
2017-04-27 17:51:06 +02:00
return; // Prior iterator failed.
}
}
2016-12-11 16:17:51 +01:00
yield $emitter->emit($value);
});
2017-04-27 17:51:06 +02:00
$previous[] = $coroutine($iterator, $emit);
$promise = Promise\all($previous);
2016-08-01 18:10:59 +02:00
}
2016-12-11 16:17:51 +01:00
2017-04-26 20:14:10 +02:00
$promise->onResolve(function ($exception) use ($emitter) {
if ($exception) {
$emitter->fail($exception);
return;
}
2016-12-11 16:17:51 +01:00
2017-04-26 20:14:10 +02:00
$emitter->complete();
});
2016-08-01 18:10:59 +02:00
2017-05-01 07:29:23 +02:00
return $emitter->iterate();
2016-05-24 18:47:14 +02:00
}
2018-10-05 21:01:57 +02:00
/**
* Collects all items from an iterator into an array.
*
* @param Iterator $iterator
*
* @return Promise<array>
*/
function toArray(Iterator $iterator): Promise
2018-10-05 21:01:57 +02:00
{
return call(function () use ($iterator) {
$array = [];
while (yield $iterator->advance()) {
$array[] = $iterator->getCurrent();
}
return $array;
});
}
2016-05-24 18:47:14 +02:00
}