2016-05-21 16:44:52 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp\Awaitable\Internal;
|
|
|
|
|
|
|
|
use Interop\Async\Loop;
|
|
|
|
|
|
|
|
class WhenQueue {
|
|
|
|
/**
|
|
|
|
* @var callable[]
|
|
|
|
*/
|
|
|
|
private $queue = [];
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable|null $callback Initial callback to add to queue.
|
|
|
|
*/
|
|
|
|
public function __construct(callable $callback = null) {
|
|
|
|
if (null !== $callback) {
|
|
|
|
$this->push($callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Calls each callback in the queue, passing the provided values to the function.
|
|
|
|
*
|
|
|
|
* @param \Throwable|\Exception|null $exception
|
|
|
|
* @param mixed $value
|
|
|
|
*/
|
|
|
|
public function __invoke($exception = null, $value = null) {
|
|
|
|
foreach ($this->queue as $callback) {
|
|
|
|
try {
|
|
|
|
$callback($exception, $value);
|
|
|
|
} catch (\Throwable $exception) {
|
2016-05-22 20:43:37 +02:00
|
|
|
Loop::defer(static function () use ($exception) {
|
2016-05-21 16:44:52 +02:00
|
|
|
throw $exception;
|
2016-05-22 20:43:37 +02:00
|
|
|
});
|
2016-05-21 16:44:52 +02:00
|
|
|
} catch (\Exception $exception) {
|
2016-05-22 20:43:37 +02:00
|
|
|
Loop::defer(static function () use ($exception) {
|
2016-05-21 16:44:52 +02:00
|
|
|
throw $exception;
|
2016-05-22 20:43:37 +02:00
|
|
|
});
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Unrolls instances of self to avoid blowing up the call stack on resolution.
|
|
|
|
*
|
|
|
|
* @param callable $callback
|
|
|
|
*/
|
2016-05-21 19:07:08 +02:00
|
|
|
public function push(callable $callback) {
|
2016-05-21 16:44:52 +02:00
|
|
|
if ($callback instanceof self) {
|
|
|
|
$this->queue = \array_merge($this->queue, $callback->queue);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->queue[] = $callback;
|
|
|
|
}
|
|
|
|
}
|