2016-12-29 14:09:49 -06:00
|
|
|
<?php
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
namespace Amp\Internal;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2017-03-27 18:37:55 -05:00
|
|
|
use Amp\Coroutine;
|
2017-03-10 15:32:58 -06:00
|
|
|
use Amp\Loop;
|
2017-03-27 18:37:55 -05:00
|
|
|
use Amp\Promise;
|
|
|
|
use React\Promise\PromiseInterface as ReactPromise;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
2016-11-14 13:59:21 -06:00
|
|
|
* Stores a set of functions to be invoked when a promise is resolved.
|
2016-06-01 12:18:11 -05:00
|
|
|
*
|
|
|
|
* @internal
|
|
|
|
*/
|
2017-03-21 17:23:37 +01:00
|
|
|
class ResolutionQueue {
|
2016-08-17 22:25:54 -05:00
|
|
|
/** @var callable[] */
|
2016-05-21 09:44:52 -05:00
|
|
|
private $queue = [];
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable|null $callback Initial callback to add to queue.
|
|
|
|
*/
|
|
|
|
public function __construct(callable $callback = null) {
|
|
|
|
if (null !== $callback) {
|
|
|
|
$this->push($callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-10 21:58:46 +01:00
|
|
|
/**
|
|
|
|
* Unrolls instances of self to avoid blowing up the call stack on resolution.
|
|
|
|
*
|
|
|
|
* @param callable $callback
|
|
|
|
*/
|
|
|
|
public function push(callable $callback) {
|
|
|
|
if ($callback instanceof self) {
|
|
|
|
$this->queue = \array_merge($this->queue, $callback->queue);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->queue[] = $callback;
|
|
|
|
}
|
|
|
|
|
2016-05-21 09:44:52 -05:00
|
|
|
/**
|
|
|
|
* Calls each callback in the queue, passing the provided values to the function.
|
|
|
|
*
|
2016-08-11 14:35:58 -05:00
|
|
|
* @param \Throwable|null $exception
|
2017-03-10 21:58:46 +01:00
|
|
|
* @param mixed $value
|
2016-05-21 09:44:52 -05:00
|
|
|
*/
|
2016-08-12 16:38:36 -05:00
|
|
|
public function __invoke($exception, $value) {
|
2016-05-21 09:44:52 -05:00
|
|
|
foreach ($this->queue as $callback) {
|
|
|
|
try {
|
2017-03-27 18:37:55 -05:00
|
|
|
$result = $callback($exception, $value);
|
|
|
|
|
|
|
|
if ($result === null) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($result instanceof \Generator) {
|
|
|
|
$result = new Coroutine($result);
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($result instanceof Promise || $result instanceof ReactPromise) {
|
|
|
|
Promise\rethrow($result);
|
|
|
|
}
|
2016-05-21 09:44:52 -05:00
|
|
|
} catch (\Throwable $exception) {
|
2017-06-05 00:21:45 -05:00
|
|
|
Loop::defer(static function () use ($exception) {
|
2017-03-10 15:32:58 -06:00
|
|
|
throw $exception;
|
|
|
|
});
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|