2016-12-02 22:14:14 +03:00
|
|
|
<?php
|
|
|
|
namespace GraphQL;
|
|
|
|
|
|
|
|
use GraphQL\Executor\Promise\Adapter\SyncPromise;
|
|
|
|
|
|
|
|
class Deferred
|
|
|
|
{
|
2016-12-04 11:49:34 +03:00
|
|
|
/**
|
|
|
|
* @var \SplQueue
|
|
|
|
*/
|
2016-12-02 22:14:14 +03:00
|
|
|
private static $queue;
|
|
|
|
|
2016-12-04 11:49:34 +03:00
|
|
|
/**
|
|
|
|
* @var callable
|
|
|
|
*/
|
2016-12-02 22:14:14 +03:00
|
|
|
private $callback;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var SyncPromise
|
|
|
|
*/
|
|
|
|
public $promise;
|
|
|
|
|
|
|
|
public static function getQueue()
|
|
|
|
{
|
|
|
|
return self::$queue ?: self::$queue = new \SplQueue();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function runQueue()
|
|
|
|
{
|
2016-12-04 11:49:34 +03:00
|
|
|
$q = self::$queue;
|
|
|
|
while ($q && !$q->isEmpty()) {
|
2016-12-02 22:14:14 +03:00
|
|
|
/** @var self $dfd */
|
|
|
|
$dfd = $q->dequeue();
|
|
|
|
$dfd->run();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __construct(callable $callback)
|
|
|
|
{
|
|
|
|
$this->callback = $callback;
|
|
|
|
$this->promise = new SyncPromise();
|
|
|
|
self::getQueue()->enqueue($this);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function then($onFulfilled = null, $onRejected = null)
|
|
|
|
{
|
|
|
|
return $this->promise->then($onFulfilled, $onRejected);
|
|
|
|
}
|
|
|
|
|
|
|
|
private function run()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$cb = $this->callback;
|
|
|
|
$this->promise->resolve($cb());
|
|
|
|
} catch (\Exception $e) {
|
|
|
|
$this->promise->reject($e);
|
2017-06-06 13:55:38 +03:00
|
|
|
} catch (\Throwable $e) {
|
|
|
|
$this->promise->reject($e);
|
2016-12-02 22:14:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|