2016-12-03 02:14:14 +07:00
|
|
|
<?php
|
2018-09-02 10:17:27 +02:00
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
2016-12-03 02:14:14 +07:00
|
|
|
namespace GraphQL;
|
|
|
|
|
2018-09-26 11:03:10 +02:00
|
|
|
use Exception;
|
2016-12-03 02:14:14 +07:00
|
|
|
use GraphQL\Executor\Promise\Adapter\SyncPromise;
|
2018-09-26 11:03:10 +02:00
|
|
|
use SplQueue;
|
|
|
|
use Throwable;
|
2016-12-03 02:14:14 +07:00
|
|
|
|
|
|
|
class Deferred
|
|
|
|
{
|
2018-12-27 22:39:16 +01:00
|
|
|
/** @var SplQueue|null */
|
2016-12-03 02:14:14 +07:00
|
|
|
private static $queue;
|
|
|
|
|
2018-09-02 10:17:27 +02:00
|
|
|
/** @var callable */
|
2016-12-03 02:14:14 +07:00
|
|
|
private $callback;
|
|
|
|
|
2018-09-02 10:17:27 +02:00
|
|
|
/** @var SyncPromise */
|
2016-12-03 02:14:14 +07:00
|
|
|
public $promise;
|
|
|
|
|
2018-12-27 22:39:16 +01:00
|
|
|
public function __construct(callable $callback)
|
2016-12-03 02:14:14 +07:00
|
|
|
{
|
2018-12-27 22:39:16 +01:00
|
|
|
$this->callback = $callback;
|
|
|
|
$this->promise = new SyncPromise();
|
|
|
|
self::getQueue()->enqueue($this);
|
2016-12-03 02:14:14 +07:00
|
|
|
}
|
|
|
|
|
2018-12-27 22:39:16 +01:00
|
|
|
public static function getQueue() : SplQueue
|
2016-12-03 02:14:14 +07:00
|
|
|
{
|
2018-12-27 22:39:16 +01:00
|
|
|
if (self::$queue === null) {
|
|
|
|
self::$queue = new SplQueue();
|
2016-12-03 02:14:14 +07:00
|
|
|
}
|
2018-12-27 22:39:16 +01:00
|
|
|
|
|
|
|
return self::$queue;
|
2016-12-03 02:14:14 +07:00
|
|
|
}
|
|
|
|
|
2018-12-27 22:39:16 +01:00
|
|
|
public static function runQueue() : void
|
2016-12-03 02:14:14 +07:00
|
|
|
{
|
2018-12-27 22:39:16 +01:00
|
|
|
$queue = self::getQueue();
|
|
|
|
while (! $queue->isEmpty()) {
|
|
|
|
/** @var self $dequeuedNodeValue */
|
|
|
|
$dequeuedNodeValue = $queue->dequeue();
|
|
|
|
$dequeuedNodeValue->run();
|
|
|
|
}
|
2016-12-03 02:14:14 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
public function then($onFulfilled = null, $onRejected = null)
|
|
|
|
{
|
|
|
|
return $this->promise->then($onFulfilled, $onRejected);
|
|
|
|
}
|
|
|
|
|
2018-09-02 10:17:27 +02:00
|
|
|
public function run() : void
|
2016-12-03 02:14:14 +07:00
|
|
|
{
|
|
|
|
try {
|
|
|
|
$cb = $this->callback;
|
|
|
|
$this->promise->resolve($cb());
|
2018-09-26 11:03:10 +02:00
|
|
|
} catch (Exception $e) {
|
2016-12-03 02:14:14 +07:00
|
|
|
$this->promise->reject($e);
|
2018-09-26 11:03:10 +02:00
|
|
|
} catch (Throwable $e) {
|
2017-06-06 12:55:38 +02:00
|
|
|
$this->promise->reject($e);
|
2016-12-03 02:14:14 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|