graphql-php/src/Deferred.php

62 lines
1.2 KiB
PHP
Raw Normal View History

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