Refactoring

This commit is contained in:
Simon Podlipsky 2018-06-26 02:15:56 +02:00
parent a032367e26
commit cd1cc911e7
No known key found for this signature in database
GPG Key ID: 725C2BD962B42663
12 changed files with 954 additions and 880 deletions

View File

@ -1,7 +1,11 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor; namespace GraphQL\Executor;
use GraphQL\Error\Error; use GraphQL\Error\Error;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentDefinitionNode;
use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Type\Schema; use GraphQL\Type\Schema;
@ -16,46 +20,33 @@ use GraphQL\Type\Schema;
*/ */
class ExecutionContext class ExecutionContext
{ {
/** /** @var Schema */
* @var Schema
*/
public $schema; public $schema;
/** /** @var FragmentDefinitionNode[] */
* @var FragmentDefinitionNode[]
*/
public $fragments; public $fragments;
/** /** @var mixed */
* @var mixed
*/
public $rootValue; public $rootValue;
/** /** @var mixed */
* @var mixed
*/
public $contextValue; public $contextValue;
/** /** @var OperationDefinitionNode */
* @var OperationDefinitionNode
*/
public $operation; public $operation;
/** /** @var mixed[] */
* @var array
*/
public $variableValues; public $variableValues;
/** /** @var callable */
* @var callable
*/
public $fieldResolver; public $fieldResolver;
/** /** @var Error[] */
* @var array
*/
public $errors; public $errors;
/** @var PromiseAdapter */
public $promises;
public function __construct( public function __construct(
$schema, $schema,
$fragments, $fragments,
@ -66,8 +57,7 @@ class ExecutionContext
$errors, $errors,
$fieldResolver, $fieldResolver,
$promiseAdapter $promiseAdapter
) ) {
{
$this->schema = $schema; $this->schema = $schema;
$this->fragments = $fragments; $this->fragments = $fragments;
$this->rootValue = $root; $this->rootValue = $root;
@ -82,6 +72,7 @@ class ExecutionContext
public function addError(Error $error) public function addError(Error $error)
{ {
$this->errors[] = $error; $this->errors[] = $error;
return $this; return $this;
} }
} }

View File

@ -1,7 +1,12 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor; namespace GraphQL\Executor;
use GraphQL\Error\Error;
use GraphQL\Error\FormattedError; use GraphQL\Error\FormattedError;
use function array_map;
/** /**
* Returned after [query execution](executing-queries.md). * Returned after [query execution](executing-queries.md).
@ -17,7 +22,7 @@ class ExecutionResult implements \JsonSerializable
* Data collected from resolvers during query execution * Data collected from resolvers during query execution
* *
* @api * @api
* @var array * @var mixed[]
*/ */
public $data; public $data;
@ -28,7 +33,7 @@ class ExecutionResult implements \JsonSerializable
* contain original exception. * contain original exception.
* *
* @api * @api
* @var \GraphQL\Error\Error[] * @var Error[]
*/ */
public $errors; public $errors;
@ -37,26 +42,22 @@ class ExecutionResult implements \JsonSerializable
* Conforms to * Conforms to
* *
* @api * @api
* @var array * @var mixed[]
*/ */
public $extensions; public $extensions;
/** /** @var callable */
* @var callable
*/
private $errorFormatter; private $errorFormatter;
/** /** @var callable */
* @var callable
*/
private $errorsHandler; private $errorsHandler;
/** /**
* @param array $data * @param mixed[] $data
* @param array $errors * @param Error[] $errors
* @param array $extensions * @param mixed[] $extensions
*/ */
public function __construct(array $data = null, array $errors = [], array $extensions = []) public function __construct(?array $data = null, array $errors = [], array $extensions = [])
{ {
$this->data = $data; $this->data = $data;
$this->errors = $errors; $this->errors = $errors;
@ -77,12 +78,12 @@ class ExecutionResult implements \JsonSerializable
* ); * );
* *
* @api * @api
* @param callable $errorFormatter
* @return $this * @return $this
*/ */
public function setErrorFormatter(callable $errorFormatter) public function setErrorFormatter(callable $errorFormatter)
{ {
$this->errorFormatter = $errorFormatter; $this->errorFormatter = $errorFormatter;
return $this; return $this;
} }
@ -97,15 +98,23 @@ class ExecutionResult implements \JsonSerializable
* } * }
* *
* @api * @api
* @param callable $handler
* @return $this * @return $this
*/ */
public function setErrorsHandler(callable $handler) public function setErrorsHandler(callable $handler)
{ {
$this->errorsHandler = $handler; $this->errorsHandler = $handler;
return $this; return $this;
} }
/**
* @return mixed[]
*/
public function jsonSerialize()
{
return $this->toArray();
}
/** /**
* Converts GraphQL query result to spec-compliant serializable array using provided * Converts GraphQL query result to spec-compliant serializable array using provided
* errors handler and formatter. * errors handler and formatter.
@ -118,40 +127,31 @@ class ExecutionResult implements \JsonSerializable
* *
* @api * @api
* @param bool|int $debug * @param bool|int $debug
* @return array * @return mixed[]
*/ */
public function toArray($debug = false) public function toArray($debug = false)
{ {
$result = []; $result = [];
if (!empty($this->errors)) { if (! empty($this->errors)) {
$errorsHandler = $this->errorsHandler ?: function(array $errors, callable $formatter) { $errorsHandler = $this->errorsHandler ?: function (array $errors, callable $formatter) {
return array_map($formatter, $errors); return array_map($formatter, $errors);
}; };
$result['errors'] = $errorsHandler( $result['errors'] = $errorsHandler(
$this->errors, $this->errors,
FormattedError::prepareFormatter($this->errorFormatter, $debug) FormattedError::prepareFormatter($this->errorFormatter, $debug)
); );
} }
if (null !== $this->data) { if ($this->data !== null) {
$result['data'] = $this->data; $result['data'] = $this->data;
} }
if (!empty($this->extensions)) { if (! empty($this->extensions)) {
$result['extensions'] = (array) $this->extensions; $result['extensions'] = (array) $this->extensions;
} }
return $result; return $result;
} }
/**
* Part of \JsonSerializable interface
*
* @return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor\Promise\Adapter; namespace GraphQL\Executor\Promise\Adapter;
use GraphQL\Executor\Promise\Promise; use GraphQL\Executor\Promise\Promise;
@ -6,6 +9,9 @@ use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Utils\Utils; use GraphQL\Utils\Utils;
use React\Promise\Promise as ReactPromise; use React\Promise\Promise as ReactPromise;
use React\Promise\PromiseInterface as ReactPromiseInterface; use React\Promise\PromiseInterface as ReactPromiseInterface;
use function React\Promise\all;
use function React\Promise\reject;
use function React\Promise\resolve;
class ReactPromiseAdapter implements PromiseAdapter class ReactPromiseAdapter implements PromiseAdapter
{ {
@ -28,10 +34,11 @@ class ReactPromiseAdapter implements PromiseAdapter
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function then(Promise $promise, callable $onFulfilled = null, callable $onRejected = null) public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null)
{ {
/** @var $adoptedPromise ReactPromiseInterface */ /** @var ReactPromiseInterface $adoptedPromise */
$adoptedPromise = $promise->adoptedPromise; $adoptedPromise = $promise->adoptedPromise;
return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this); return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this);
} }
@ -41,6 +48,7 @@ class ReactPromiseAdapter implements PromiseAdapter
public function create(callable $resolver) public function create(callable $resolver)
{ {
$promise = new ReactPromise($resolver); $promise = new ReactPromise($resolver);
return new Promise($promise, $this); return new Promise($promise, $this);
} }
@ -49,7 +57,8 @@ class ReactPromiseAdapter implements PromiseAdapter
*/ */
public function createFulfilled($value = null) public function createFulfilled($value = null)
{ {
$promise = \React\Promise\resolve($value); $promise = resolve($value);
return new Promise($promise, $this); return new Promise($promise, $this);
} }
@ -58,7 +67,8 @@ class ReactPromiseAdapter implements PromiseAdapter
*/ */
public function createRejected($reason) public function createRejected($reason)
{ {
$promise = \React\Promise\reject($reason); $promise = reject($reason);
return new Promise($promise, $this); return new Promise($promise, $this);
} }
@ -68,11 +78,14 @@ class ReactPromiseAdapter implements PromiseAdapter
public function all(array $promisesOrValues) public function all(array $promisesOrValues)
{ {
// TODO: rework with generators when PHP minimum required version is changed to 5.5+ // TODO: rework with generators when PHP minimum required version is changed to 5.5+
$promisesOrValues = Utils::map($promisesOrValues, function ($item) { $promisesOrValues = Utils::map(
$promisesOrValues,
function ($item) {
return $item instanceof Promise ? $item->adoptedPromise : $item; return $item instanceof Promise ? $item->adoptedPromise : $item;
}); }
);
$promise = \React\Promise\all($promisesOrValues)->then(function($values) use ($promisesOrValues) { $promise = all($promisesOrValues)->then(function ($values) use ($promisesOrValues) {
$orderedResults = []; $orderedResults = [];
foreach ($promisesOrValues as $key => $value) { foreach ($promisesOrValues as $key => $value) {
@ -81,6 +94,7 @@ class ReactPromiseAdapter implements PromiseAdapter
return $orderedResults; return $orderedResults;
}); });
return new Promise($promise, $this); return new Promise($promise, $this);
} }
} }

View File

@ -1,15 +1,20 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor\Promise\Adapter; namespace GraphQL\Executor\Promise\Adapter;
use GraphQL\Executor\ExecutionResult;
use GraphQL\Utils\Utils; use GraphQL\Utils\Utils;
use Throwable;
use function is_object;
use function method_exists;
/** /**
* Class SyncPromise * Class SyncPromise
* *
* Simplistic (yet full-featured) implementation of Promises A+ spec for regular PHP `sync` mode * Simplistic (yet full-featured) implementation of Promises A+ spec for regular PHP `sync` mode
* (using queue to defer promises execution) * (using queue to defer promises execution)
*
* @package GraphQL\Executor\Promise\Adapter
*/ */
class SyncPromise class SyncPromise
{ {
@ -17,38 +22,69 @@ class SyncPromise
const FULFILLED = 'fulfilled'; const FULFILLED = 'fulfilled';
const REJECTED = 'rejected'; const REJECTED = 'rejected';
/** /** @var \SplQueue */
* @var \SplQueue
*/
public static $queue; public static $queue;
public static function getQueue() /** @var string */
{ public $state = self::PENDING;
return self::$queue ?: self::$queue = new \SplQueue();
} /** @var ExecutionResult|Throwable */
public $result;
/**
* Promises created in `then` method of this promise and awaiting for resolution of this promise
* @var mixed[][]
*/
private $waiting = [];
public static function runQueue() public static function runQueue()
{ {
$q = self::$queue; $q = self::$queue;
while ($q && !$q->isEmpty()) { while ($q && ! $q->isEmpty()) {
$task = $q->dequeue(); $task = $q->dequeue();
$task(); $task();
} }
} }
public $state = self::PENDING; public function resolve($value)
{
switch ($this->state) {
case self::PENDING:
if ($value === $this) {
throw new \Exception('Cannot resolve promise with self');
}
if (is_object($value) && method_exists($value, 'then')) {
$value->then(
function ($resolvedValue) {
$this->resolve($resolvedValue);
},
function ($reason) {
$this->reject($reason);
}
);
public $result; return $this;
}
/** $this->state = self::FULFILLED;
* Promises created in `then` method of this promise and awaiting for resolution of this promise $this->result = $value;
* @var array $this->enqueueWaitingPromises();
*/ break;
private $waiting = []; case self::FULFILLED:
if ($this->result !== $value) {
throw new \Exception('Cannot change value of fulfilled promise');
}
break;
case self::REJECTED:
throw new \Exception('Cannot resolve rejected promise');
}
return $this;
}
public function reject($reason) public function reject($reason)
{ {
if (!$reason instanceof \Exception && !$reason instanceof \Throwable) { if (! $reason instanceof \Exception && ! $reason instanceof \Throwable) {
throw new \Exception('SyncPromise::reject() has to be called with an instance of \Throwable'); throw new \Exception('SyncPromise::reject() has to be called with an instance of \Throwable');
} }
@ -60,70 +96,22 @@ class SyncPromise
break; break;
case self::REJECTED: case self::REJECTED:
if ($reason !== $this->result) { if ($reason !== $this->result) {
throw new \Exception("Cannot change rejection reason"); throw new \Exception('Cannot change rejection reason');
} }
break; break;
case self::FULFILLED: case self::FULFILLED:
throw new \Exception("Cannot reject fulfilled promise"); throw new \Exception('Cannot reject fulfilled promise');
}
return $this;
} }
public function resolve($value)
{
switch ($this->state) {
case self::PENDING:
if ($value === $this) {
throw new \Exception("Cannot resolve promise with self");
}
if (is_object($value) && method_exists($value, 'then')) {
$value->then(
function($resolvedValue) {
$this->resolve($resolvedValue);
},
function($reason) {
$this->reject($reason);
}
);
return $this; return $this;
} }
$this->state = self::FULFILLED;
$this->result = $value;
$this->enqueueWaitingPromises();
break;
case self::FULFILLED:
if ($this->result !== $value) {
throw new \Exception("Cannot change value of fulfilled promise");
}
break;
case self::REJECTED:
throw new \Exception("Cannot resolve rejected promise");
}
return $this;
}
public function then(callable $onFulfilled = null, callable $onRejected = null)
{
if ($this->state === self::REJECTED && !$onRejected) {
return $this;
}
if ($this->state === self::FULFILLED && !$onFulfilled) {
return $this;
}
$tmp = new self();
$this->waiting[] = [$tmp, $onFulfilled, $onRejected];
if ($this->state !== self::PENDING) {
$this->enqueueWaitingPromises();
}
return $tmp;
}
private function enqueueWaitingPromises() private function enqueueWaitingPromises()
{ {
Utils::invariant($this->state !== self::PENDING, 'Cannot enqueue derived promises when parent is still pending'); Utils::invariant(
$this->state !== self::PENDING,
'Cannot enqueue derived promises when parent is still pending'
);
foreach ($this->waiting as $descriptor) { foreach ($this->waiting as $descriptor) {
self::getQueue()->enqueue(function () use ($descriptor) { self::getQueue()->enqueue(function () use ($descriptor) {
@ -138,7 +126,7 @@ class SyncPromise
} catch (\Throwable $e) { } catch (\Throwable $e) {
$promise->reject($e); $promise->reject($e);
} }
} else if ($this->state === self::REJECTED) { } elseif ($this->state === self::REJECTED) {
try { try {
if ($onRejected) { if ($onRejected) {
$promise->resolve($onRejected($this->result)); $promise->resolve($onRejected($this->result));
@ -155,4 +143,27 @@ class SyncPromise
} }
$this->waiting = []; $this->waiting = [];
} }
public static function getQueue()
{
return self::$queue ?: self::$queue = new \SplQueue();
}
public function then(?callable $onFulfilled = null, ?callable $onRejected = null)
{
if ($this->state === self::REJECTED && ! $onRejected) {
return $this;
}
if ($this->state === self::FULFILLED && ! $onFulfilled) {
return $this;
}
$tmp = new self();
$this->waiting[] = [$tmp, $onFulfilled, $onRejected];
if ($this->state !== self::PENDING) {
$this->enqueueWaitingPromises();
}
return $tmp;
}
} }

View File

@ -1,19 +1,20 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor\Promise\Adapter; namespace GraphQL\Executor\Promise\Adapter;
use GraphQL\Deferred; use GraphQL\Deferred;
use GraphQL\Error\InvariantViolation; use GraphQL\Error\InvariantViolation;
use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\Promise\Promise; use GraphQL\Executor\Promise\Promise;
use GraphQL\Executor\Promise\PromiseAdapter; use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Utils\Utils; use GraphQL\Utils\Utils;
use function count;
/** /**
* Class SyncPromiseAdapter
*
* Allows changing order of field resolution even in sync environments * Allows changing order of field resolution even in sync environments
* (by leveraging queue of deferreds and promises) * (by leveraging queue of deferreds and promises)
*
* @package GraphQL\Executor\Promise\Adapter
*/ */
class SyncPromiseAdapter implements PromiseAdapter class SyncPromiseAdapter implements PromiseAdapter
{ {
@ -30,20 +31,22 @@ class SyncPromiseAdapter implements PromiseAdapter
*/ */
public function convertThenable($thenable) public function convertThenable($thenable)
{ {
if (!$thenable instanceof Deferred) { if (! $thenable instanceof Deferred) {
throw new InvariantViolation('Expected instance of GraphQL\Deferred, got ' . Utils::printSafe($thenable)); throw new InvariantViolation('Expected instance of GraphQL\Deferred, got ' . Utils::printSafe($thenable));
} }
return new Promise($thenable->promise, $this); return new Promise($thenable->promise, $this);
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function then(Promise $promise, callable $onFulfilled = null, callable $onRejected = null) public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null)
{ {
/** @var SyncPromise $promise */ /** @var SyncPromise $adoptedPromise */
$promise = $promise->adoptedPromise; $adoptedPromise = $promise->adoptedPromise;
return new Promise($promise->then($onFulfilled, $onRejected), $this);
return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this);
} }
/** /**
@ -55,8 +58,14 @@ class SyncPromiseAdapter implements PromiseAdapter
try { try {
$resolver( $resolver(
[$promise, 'resolve'], [
[$promise, 'reject'] $promise,
'resolve',
],
[
$promise,
'reject',
]
); );
} catch (\Exception $e) { } catch (\Exception $e) {
$promise->reject($e); $promise->reject($e);
@ -73,6 +82,7 @@ class SyncPromiseAdapter implements PromiseAdapter
public function createFulfilled($value = null) public function createFulfilled($value = null)
{ {
$promise = new SyncPromise(); $promise = new SyncPromise();
return new Promise($promise->resolve($value), $this); return new Promise($promise->resolve($value), $this);
} }
@ -82,6 +92,7 @@ class SyncPromiseAdapter implements PromiseAdapter
public function createRejected($reason) public function createRejected($reason)
{ {
$promise = new SyncPromise(); $promise = new SyncPromise();
return new Promise($promise->reject($reason), $this); return new Promise($promise->reject($reason), $this);
} }
@ -100,12 +111,14 @@ class SyncPromiseAdapter implements PromiseAdapter
if ($promiseOrValue instanceof Promise) { if ($promiseOrValue instanceof Promise) {
$result[$index] = null; $result[$index] = null;
$promiseOrValue->then( $promiseOrValue->then(
function($value) use ($index, &$count, $total, &$result, $all) { function ($value) use ($index, &$count, $total, &$result, $all) {
$result[$index] = $value; $result[$index] = $value;
$count++; $count++;
if ($count >= $total) { if ($count < $total) {
$all->resolve($result); return;
} }
$all->resolve($result);
}, },
[$all, 'reject'] [$all, 'reject']
); );
@ -117,14 +130,14 @@ class SyncPromiseAdapter implements PromiseAdapter
if ($count === $total) { if ($count === $total) {
$all->resolve($result); $all->resolve($result);
} }
return new Promise($all, $this); return new Promise($all, $this);
} }
/** /**
* Synchronously wait when promise completes * Synchronously wait when promise completes
* *
* @param Promise $promise * @return ExecutionResult
* @return mixed
*/ */
public function wait(Promise $promise) public function wait(Promise $promise)
{ {
@ -132,9 +145,8 @@ class SyncPromiseAdapter implements PromiseAdapter
$dfdQueue = Deferred::getQueue(); $dfdQueue = Deferred::getQueue();
$promiseQueue = SyncPromise::getQueue(); $promiseQueue = SyncPromise::getQueue();
while ( while ($promise->adoptedPromise->state === SyncPromise::PENDING &&
$promise->adoptedPromise->state === SyncPromise::PENDING && ! ($dfdQueue->isEmpty() && $promiseQueue->isEmpty())
!($dfdQueue->isEmpty() && $promiseQueue->isEmpty())
) { ) {
Deferred::runQueue(); Deferred::runQueue();
SyncPromise::runQueue(); SyncPromise::runQueue();
@ -146,17 +158,16 @@ class SyncPromiseAdapter implements PromiseAdapter
if ($syncPromise->state === SyncPromise::FULFILLED) { if ($syncPromise->state === SyncPromise::FULFILLED) {
return $syncPromise->result; return $syncPromise->result;
} else if ($syncPromise->state === SyncPromise::REJECTED) { } elseif ($syncPromise->state === SyncPromise::REJECTED) {
throw $syncPromise->result; throw $syncPromise->result;
} }
throw new InvariantViolation("Could not resolve promise"); throw new InvariantViolation('Could not resolve promise');
} }
/** /**
* Execute just before starting to run promise completion * Execute just before starting to run promise completion
* *
* @param Promise $promise
*/ */
protected function beforeWait(Promise $promise) protected function beforeWait(Promise $promise)
{ {
@ -165,7 +176,6 @@ class SyncPromiseAdapter implements PromiseAdapter
/** /**
* Execute while running promise completion * Execute while running promise completion
* *
* @param Promise $promise
*/ */
protected function onWait(Promise $promise) protected function onWait(Promise $promise)
{ {

View File

@ -1,6 +1,10 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor\Promise; namespace GraphQL\Executor\Promise;
use GraphQL\Executor\Promise\Adapter\SyncPromise;
use GraphQL\Utils\Utils; use GraphQL\Utils\Utils;
/** /**
@ -8,31 +12,28 @@ use GraphQL\Utils\Utils;
*/ */
class Promise class Promise
{ {
private $adapter; /** @var SyncPromise|ReactPromise */
public $adoptedPromise; public $adoptedPromise;
/** @var PromiseAdapter */
private $adapter;
/** /**
* Promise constructor.
*
* @param mixed $adoptedPromise * @param mixed $adoptedPromise
* @param PromiseAdapter $adapter
*/ */
public function __construct($adoptedPromise, PromiseAdapter $adapter) public function __construct($adoptedPromise, PromiseAdapter $adapter)
{ {
Utils::invariant(!$adoptedPromise instanceof self, 'Expecting promise from adapted system, got ' . __CLASS__); Utils::invariant(! $adoptedPromise instanceof self, 'Expecting promise from adapted system, got ' . __CLASS__);
$this->adapter = $adapter; $this->adapter = $adapter;
$this->adoptedPromise = $adoptedPromise; $this->adoptedPromise = $adoptedPromise;
} }
/** /**
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* *
* @return Promise * @return Promise
*/ */
public function then(callable $onFulfilled = null, callable $onRejected = null) public function then(?callable $onFulfilled = null, ?callable $onRejected = null)
{ {
return $this->adapter->then($this, $onFulfilled, $onRejected); return $this->adapter->then($this, $onFulfilled, $onRejected);
} }

View File

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor\Promise; namespace GraphQL\Executor\Promise;
/** /**
@ -29,13 +32,10 @@ interface PromiseAdapter
* in Promises/A+ specs. Then returns new wrapped instance of GraphQL\Executor\Promise\Promise. * in Promises/A+ specs. Then returns new wrapped instance of GraphQL\Executor\Promise\Promise.
* *
* @api * @api
* @param Promise $promise
* @param callable|null $onFulfilled
* @param callable|null $onRejected
* *
* @return Promise * @return Promise
*/ */
public function then(Promise $promise, callable $onFulfilled = null, callable $onRejected = null); public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null);
/** /**
* Creates a Promise * Creates a Promise
@ -44,7 +44,6 @@ interface PromiseAdapter
* function(callable $resolve, callable $reject) * function(callable $resolve, callable $reject)
* *
* @api * @api
* @param callable $resolver
* @return Promise * @return Promise
*/ */
public function create(callable $resolver); public function create(callable $resolver);
@ -73,7 +72,7 @@ interface PromiseAdapter
* items in the array are fulfilled. * items in the array are fulfilled.
* *
* @api * @api
* @param array $promisesOrValues Promises or values. * @param Promise[]|mixed[] $promisesOrValues Promises or values.
* @return Promise * @return Promise
*/ */
public function all(array $promisesOrValues); public function all(array $promisesOrValues);

View File

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace GraphQL\Executor; namespace GraphQL\Executor;
use GraphQL\Error\Error; use GraphQL\Error\Error;
@ -10,19 +13,24 @@ use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\FragmentSpreadNode;
use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\InlineFragmentNode;
use GraphQL\Language\AST\NodeList; use GraphQL\Language\AST\NodeList;
use GraphQL\Language\AST\VariableNode; use GraphQL\Language\AST\ValueNode;
use GraphQL\Language\AST\VariableDefinitionNode; use GraphQL\Language\AST\VariableDefinitionNode;
use GraphQL\Language\AST\VariableNode;
use GraphQL\Language\Printer; use GraphQL\Language\Printer;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\FieldDefinition; use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\InputType; use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\Utils\AST; use GraphQL\Utils\AST;
use GraphQL\Utils\TypeInfo; use GraphQL\Utils\TypeInfo;
use GraphQL\Utils\Utils; use GraphQL\Utils\Utils;
use GraphQL\Utils\Value; use GraphQL\Utils\Value;
use Throwable;
use function array_key_exists;
use function array_map;
use function sprintf;
class Values class Values
{ {
@ -31,10 +39,9 @@ class Values
* variable definitions and arbitrary input. If the input cannot be coerced * variable definitions and arbitrary input. If the input cannot be coerced
* to match the variable definitions, a Error will be thrown. * to match the variable definitions, a Error will be thrown.
* *
* @param Schema $schema
* @param VariableDefinitionNode[] $varDefNodes * @param VariableDefinitionNode[] $varDefNodes
* @param array $inputs * @param mixed[] $inputs
* @return array * @return mixed[]
*/ */
public static function getVariableValues(Schema $schema, $varDefNodes, array $inputs) public static function getVariableValues(Schema $schema, $varDefNodes, array $inputs)
{ {
@ -45,21 +52,27 @@ class Values
/** @var InputType|Type $varType */ /** @var InputType|Type $varType */
$varType = TypeInfo::typeFromAST($schema, $varDefNode->type); $varType = TypeInfo::typeFromAST($schema, $varDefNode->type);
if (!Type::isInputType($varType)) { if (! Type::isInputType($varType)) {
$errors[] = new Error( $errors[] = new Error(
"Variable \"\$$varName\" expected value of type " . sprintf(
'"' . Printer::doPrint($varDefNode->type) . '" which cannot be used as an input type.', 'Variable "$%s" expected value of type "%s" which cannot be used as an input type.',
$varName,
Printer::doPrint($varDefNode->type)
),
[$varDefNode->type] [$varDefNode->type]
); );
} else { } else {
if (!array_key_exists($varName, $inputs)) { if (! array_key_exists($varName, $inputs)) {
if ($varType instanceof NonNull) { if ($varType instanceof NonNull) {
$errors[] = new Error( $errors[] = new Error(
"Variable \"\$$varName\" of required type " . sprintf(
"\"{$varType}\" was not provided.", 'Variable "$%s" of required type "%s" was not provided.',
$varName,
$varType
),
[$varDefNode] [$varDefNode]
); );
} else if ($varDefNode->defaultValue) { } elseif ($varDefNode->defaultValue) {
$coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType); $coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType);
} }
} else { } else {
@ -67,10 +80,14 @@ class Values
$coerced = Value::coerceValue($value, $varType, $varDefNode); $coerced = Value::coerceValue($value, $varType, $varDefNode);
/** @var Error[] $coercionErrors */ /** @var Error[] $coercionErrors */
$coercionErrors = $coerced['errors']; $coercionErrors = $coerced['errors'];
if ($coercionErrors) { if (! empty($coercionErrors)) {
$messagePrelude = "Variable \"\$$varName\" got invalid value " . Utils::printSafeJson($value) . '; '; $messagePrelude = sprintf(
'Variable "$%s" got invalid value %s; ',
$varName,
Utils::printSafeJson($value)
);
foreach($coercionErrors as $error) { foreach ($coercionErrors as $error) {
$errors[] = new Error( $errors[] = new Error(
$messagePrelude . $error->getMessage(), $messagePrelude . $error->getMessage(),
$error->getNodes(), $error->getNodes(),
@ -87,17 +104,48 @@ class Values
} }
} }
} }
return ['errors' => $errors, 'coerced' => $errors ? null : $coercedValues]; return ['errors' => $errors, 'coerced' => $errors ? null : $coercedValues];
} }
/**
* Prepares an object map of argument values given a directive definition
* and a AST node which may contain directives. Optionally also accepts a map
* of variable values.
*
* If the directive does not exist on the node, returns undefined.
*
* @param FragmentSpreadNode|FieldNode|InlineFragmentNode|EnumValueDefinitionNode|FieldDefinitionNode $node
* @param mixed[]|null $variableValues
*
* @return mixed[]|null
*/
public static function getDirectiveValues(Directive $directiveDef, $node, $variableValues = null)
{
if (isset($node->directives) && $node->directives instanceof NodeList) {
$directiveNode = Utils::find(
$node->directives,
function (DirectiveNode $directive) use ($directiveDef) {
return $directive->name->value === $directiveDef->name;
}
);
if ($directiveNode) {
return self::getArgumentValues($directiveDef, $directiveNode, $variableValues);
}
}
return null;
}
/** /**
* Prepares an object map of argument values given a list of argument * Prepares an object map of argument values given a list of argument
* definitions and list of argument AST nodes. * definitions and list of argument AST nodes.
* *
* @param FieldDefinition|Directive $def * @param FieldDefinition|Directive $def
* @param FieldNode|\GraphQL\Language\AST\DirectiveNode $node * @param FieldNode|DirectiveNode $node
* @param $variableValues * @param mixed[] $variableValues
* @return array * @return mixed[]
* @throws Error * @throws Error
*/ */
public static function getArgumentValues($def, $node, $variableValues = null) public static function getArgumentValues($def, $node, $variableValues = null)
@ -105,33 +153,36 @@ class Values
$argDefs = $def->args; $argDefs = $def->args;
$argNodes = $node->arguments; $argNodes = $node->arguments;
if (!$argDefs || null === $argNodes) { if (empty($argDefs) || $argNodes === null) {
return []; return [];
} }
$coercedValues = []; $coercedValues = [];
/** @var ArgumentNode[] $argNodeMap */ /** @var ArgumentNode[] $argNodeMap */
$argNodeMap = $argNodes ? Utils::keyMap($argNodes, function (ArgumentNode $arg) { $argNodeMap = $argNodes ? Utils::keyMap(
$argNodes,
function (ArgumentNode $arg) {
return $arg->name->value; return $arg->name->value;
}) : []; }
) : [];
foreach ($argDefs as $argDef) { foreach ($argDefs as $argDef) {
$name = $argDef->name; $name = $argDef->name;
$argType = $argDef->getType(); $argType = $argDef->getType();
$argumentNode = isset($argNodeMap[$name]) ? $argNodeMap[$name] : null; $argumentNode = $argNodeMap[$name] ?? null;
if (!$argumentNode) { if (! $argumentNode) {
if ($argDef->defaultValueExists()) { if ($argDef->defaultValueExists()) {
$coercedValues[$name] = $argDef->defaultValue; $coercedValues[$name] = $argDef->defaultValue;
} else if ($argType instanceof NonNull) { } elseif ($argType instanceof NonNull) {
throw new Error( throw new Error(
'Argument "' . $name . '" of required type ' . 'Argument "' . $name . '" of required type ' .
'"' . Utils::printSafe($argType) . '" was not provided.', '"' . Utils::printSafe($argType) . '" was not provided.',
[$node] [$node]
); );
} }
} else if ($argumentNode->value instanceof VariableNode) { } elseif ($argumentNode->value instanceof VariableNode) {
$variableName = $argumentNode->value->name->value; $variableName = $argumentNode->value->name->value;
if ($variableValues && array_key_exists($variableName, $variableValues)) { if ($variableValues && array_key_exists($variableName, $variableValues)) {
@ -139,14 +190,14 @@ class Values
// This assumes that this query has been validated and the variable // This assumes that this query has been validated and the variable
// usage here is of the correct type. // usage here is of the correct type.
$coercedValues[$name] = $variableValues[$variableName]; $coercedValues[$name] = $variableValues[$variableName];
} else if ($argDef->defaultValueExists()) { } elseif ($argDef->defaultValueExists()) {
$coercedValues[$name] = $argDef->defaultValue; $coercedValues[$name] = $argDef->defaultValue;
} else if ($argType instanceof NonNull) { } elseif ($argType instanceof NonNull) {
throw new Error( throw new Error(
'Argument "' . $name . '" of required type "' . Utils::printSafe($argType) . '" was ' . 'Argument "' . $name . '" of required type "' . Utils::printSafe($argType) . '" was ' .
'provided the variable "$' . $variableName . '" which was not provided ' . 'provided the variable "$' . $variableName . '" which was not provided ' .
'a runtime value.', 'a runtime value.',
[ $argumentNode->value ] [$argumentNode->value]
); );
} }
} else { } else {
@ -158,49 +209,22 @@ class Values
// continue with an invalid argument value. // continue with an invalid argument value.
throw new Error( throw new Error(
'Argument "' . $name . '" has invalid value ' . Printer::doPrint($valueNode) . '.', 'Argument "' . $name . '" has invalid value ' . Printer::doPrint($valueNode) . '.',
[ $argumentNode->value ] [$argumentNode->value]
); );
} }
$coercedValues[$name] = $coercedValue; $coercedValues[$name] = $coercedValue;
} }
} }
return $coercedValues; return $coercedValues;
} }
/**
* Prepares an object map of argument values given a directive definition
* and a AST node which may contain directives. Optionally also accepts a map
* of variable values.
*
* If the directive does not exist on the node, returns undefined.
*
* @param Directive $directiveDef
* @param FragmentSpreadNode | FieldNode | InlineFragmentNode | EnumValueDefinitionNode | FieldDefinitionNode $node
* @param array|null $variableValues
*
* @return array|null
*/
public static function getDirectiveValues(Directive $directiveDef, $node, $variableValues = null)
{
if (isset($node->directives) && $node->directives instanceof NodeList) {
$directiveNode = Utils::find($node->directives, function(DirectiveNode $directive) use ($directiveDef) {
return $directive->name->value === $directiveDef->name;
});
if ($directiveNode) {
return self::getArgumentValues($directiveDef, $directiveNode, $variableValues);
}
}
return null;
}
/** /**
* @deprecated as of 8.0 (Moved to \GraphQL\Utils\AST::valueFromAST) * @deprecated as of 8.0 (Moved to \GraphQL\Utils\AST::valueFromAST)
* *
* @param $valueNode * @param ValueNode $valueNode
* @param InputType $type
* @param null $variables * @param null $variables
* @return array|null|\stdClass * @return mixed[]|null|\stdClass
*/ */
public static function valueFromAST($valueNode, InputType $type, $variables = null) public static function valueFromAST($valueNode, InputType $type, $variables = null)
{ {
@ -209,15 +233,19 @@ class Values
/** /**
* @deprecated as of 0.12 (Use coerceValue() directly for richer information) * @deprecated as of 0.12 (Use coerceValue() directly for richer information)
* @param $value * @param mixed[] $value
* @param InputType $type * @return string[]
* @return array
*/ */
public static function isValidPHPValue($value, InputType $type) public static function isValidPHPValue($value, InputType $type)
{ {
$errors = Value::coerceValue($value, $type)['errors']; $errors = Value::coerceValue($value, $type)['errors'];
return $errors return $errors
? array_map(function(/*\Throwable */$error) { return $error->getMessage(); }, $errors) ? array_map(
: []; function (Throwable $error) {
return $error->getMessage();
},
$errors
) : [];
} }
} }

View File

@ -189,7 +189,7 @@ class Helper
* @api * @api
* @param ServerConfig $config * @param ServerConfig $config
* @param OperationParams[] $operations * @param OperationParams[] $operations
* @return ExecutionResult[]|Promise * @return ExecutionResult|ExecutionResult[]|Promise
*/ */
public function executeBatch(ServerConfig $config, array $operations) public function executeBatch(ServerConfig $config, array $operations)
{ {

View File

@ -282,7 +282,7 @@ class AST
* @api * @api
* @param $valueNode * @param $valueNode
* @param InputType $type * @param InputType $type
* @param null $variables * @param mixed[]|null $variables
* @return array|null|\stdClass * @return array|null|\stdClass
* @throws \Exception * @throws \Exception
*/ */

View File

@ -59,7 +59,7 @@ class Utils
/** /**
* @param array|Traversable $traversable * @param array|Traversable $traversable
* @param callable $predicate * @param callable $predicate
* @return null * @return mixed|null
*/ */
public static function find($traversable, callable $predicate) public static function find($traversable, callable $predicate)
{ {