Version 4.6.0
This commit is contained in:
1 parent
f79dcf067a
commit
517a5e1f70
2036 files changed
+110041
-26162
No files matched your search
+29
-38
@@ -1,7 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor;
|
||||
|
||||
use GraphQL\Error\Error;
|
||||
use GraphQL\Executor\Promise\PromiseAdapter;
|
||||
use GraphQL\Language\AST\FragmentDefinitionNode;
|
||||
use GraphQL\Language\AST\OperationDefinitionNode;
|
||||
use GraphQL\Type\Schema;
|
||||
@@ -10,78 +14,65 @@ use GraphQL\Type\Schema;
|
||||
* Data that must be available at all points during query execution.
|
||||
*
|
||||
* Namely, schema of the type system that is currently executing,
|
||||
* and the fragments defined in the query document
|
||||
* and the fragments defined in the query document.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class ExecutionContext
|
||||
{
|
||||
/**
|
||||
* @var Schema
|
||||
*/
|
||||
/** @var Schema */
|
||||
public $schema;
|
||||
|
||||
/**
|
||||
* @var FragmentDefinitionNode[]
|
||||
*/
|
||||
/** @var FragmentDefinitionNode[] */
|
||||
public $fragments;
|
||||
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
/** @var mixed */
|
||||
public $rootValue;
|
||||
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
/** @var mixed */
|
||||
public $contextValue;
|
||||
|
||||
/**
|
||||
* @var OperationDefinitionNode
|
||||
*/
|
||||
/** @var OperationDefinitionNode */
|
||||
public $operation;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
/** @var mixed[] */
|
||||
public $variableValues;
|
||||
|
||||
/**
|
||||
* @var callable
|
||||
*/
|
||||
/** @var callable */
|
||||
public $fieldResolver;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
/** @var Error[] */
|
||||
public $errors;
|
||||
|
||||
/** @var PromiseAdapter */
|
||||
public $promiseAdapter;
|
||||
|
||||
public function __construct(
|
||||
$schema,
|
||||
$fragments,
|
||||
$root,
|
||||
$rootValue,
|
||||
$contextValue,
|
||||
$operation,
|
||||
$variables,
|
||||
$variableValues,
|
||||
$errors,
|
||||
$fieldResolver,
|
||||
$promiseAdapter
|
||||
)
|
||||
{
|
||||
$this->schema = $schema;
|
||||
$this->fragments = $fragments;
|
||||
$this->rootValue = $root;
|
||||
$this->contextValue = $contextValue;
|
||||
$this->operation = $operation;
|
||||
$this->variableValues = $variables;
|
||||
$this->errors = $errors ?: [];
|
||||
$this->fieldResolver = $fieldResolver;
|
||||
$this->promises = $promiseAdapter;
|
||||
) {
|
||||
$this->schema = $schema;
|
||||
$this->fragments = $fragments;
|
||||
$this->rootValue = $rootValue;
|
||||
$this->contextValue = $contextValue;
|
||||
$this->operation = $operation;
|
||||
$this->variableValues = $variableValues;
|
||||
$this->errors = $errors ?? [];
|
||||
$this->fieldResolver = $fieldResolver;
|
||||
$this->promiseAdapter = $promiseAdapter;
|
||||
}
|
||||
|
||||
public function addError(Error $error)
|
||||
{
|
||||
$this->errors[] = $error;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+51
-43
@@ -1,8 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor;
|
||||
|
||||
use GraphQL\Error\DebugFlag;
|
||||
use GraphQL\Error\Error;
|
||||
use GraphQL\Error\FormattedError;
|
||||
use JsonSerializable;
|
||||
use function array_map;
|
||||
use function count;
|
||||
|
||||
/**
|
||||
* Returned after [query execution](executing-queries.md).
|
||||
@@ -12,13 +19,13 @@ use GraphQL\Error\FormattedError;
|
||||
* Could be converted to [spec-compliant](https://facebook.github.io/graphql/#sec-Response-Format)
|
||||
* serializable array using `toArray()`
|
||||
*/
|
||||
class ExecutionResult implements \JsonSerializable
|
||||
class ExecutionResult implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* Data collected from resolvers during query execution
|
||||
*
|
||||
* @api
|
||||
* @var array
|
||||
* @var mixed[]
|
||||
*/
|
||||
public $data;
|
||||
|
||||
@@ -29,38 +36,34 @@ class ExecutionResult implements \JsonSerializable
|
||||
* contain original exception.
|
||||
*
|
||||
* @api
|
||||
* @var \GraphQL\Error\Error[]
|
||||
* @var Error[]
|
||||
*/
|
||||
public $errors;
|
||||
|
||||
|
||||
/**
|
||||
* User-defined serializable array of extensions included in serialized result.
|
||||
* Conforms to
|
||||
*
|
||||
* @api
|
||||
* @var array
|
||||
* @var mixed[]
|
||||
*/
|
||||
public $extensions;
|
||||
|
||||
/**
|
||||
* @var callable
|
||||
*/
|
||||
/** @var callable */
|
||||
private $errorFormatter;
|
||||
|
||||
/**
|
||||
* @var callable
|
||||
*/
|
||||
/** @var callable */
|
||||
private $errorsHandler;
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param array $errors
|
||||
* @param array $extensions
|
||||
* @param mixed[] $data
|
||||
* @param Error[] $errors
|
||||
* @param mixed[] $extensions
|
||||
*/
|
||||
public function __construct(array $data = null, array $errors = [], array $extensions = [])
|
||||
public function __construct($data = null, array $errors = [], array $extensions = [])
|
||||
{
|
||||
$this->data = $data;
|
||||
$this->errors = $errors;
|
||||
$this->data = $data;
|
||||
$this->errors = $errors;
|
||||
$this->extensions = $extensions;
|
||||
}
|
||||
|
||||
@@ -77,13 +80,14 @@ class ExecutionResult implements \JsonSerializable
|
||||
* // ... other keys
|
||||
* );
|
||||
*
|
||||
* @return self
|
||||
*
|
||||
* @api
|
||||
* @param callable $errorFormatter
|
||||
* @return $this
|
||||
*/
|
||||
public function setErrorFormatter(callable $errorFormatter)
|
||||
{
|
||||
$this->errorFormatter = $errorFormatter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -97,16 +101,25 @@ class ExecutionResult implements \JsonSerializable
|
||||
* return array_map($formatter, $errors);
|
||||
* }
|
||||
*
|
||||
* @return self
|
||||
*
|
||||
* @api
|
||||
* @param callable $handler
|
||||
* @return $this
|
||||
*/
|
||||
public function setErrorsHandler(callable $handler)
|
||||
{
|
||||
$this->errorsHandler = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed[]
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts GraphQL query result to spec-compliant serializable array using provided
|
||||
* errors handler and formatter.
|
||||
@@ -114,45 +127,40 @@ class ExecutionResult implements \JsonSerializable
|
||||
* If debug argument is passed, output of error formatter is enriched which debugging information
|
||||
* ("debugMessage", "trace" keys depending on flags).
|
||||
*
|
||||
* $debug argument must be either bool (only adds "debugMessage" to result) or sum of flags from
|
||||
* GraphQL\Error\Debug
|
||||
* $debug argument must sum of flags from @see \GraphQL\Error\DebugFlag
|
||||
*
|
||||
* @return mixed[]
|
||||
*
|
||||
* @api
|
||||
* @param bool|int $debug
|
||||
* @return array
|
||||
*/
|
||||
public function toArray($debug = false)
|
||||
public function toArray(int $debug = DebugFlag::NONE) : array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if (!empty($this->errors)) {
|
||||
$errorsHandler = $this->errorsHandler ?: function(array $errors, callable $formatter) {
|
||||
if (count($this->errors ?? []) > 0) {
|
||||
$errorsHandler = $this->errorsHandler ?? static function (array $errors, callable $formatter) : array {
|
||||
return array_map($formatter, $errors);
|
||||
};
|
||||
$result['errors'] = $errorsHandler(
|
||||
|
||||
$handledErrors = $errorsHandler(
|
||||
$this->errors,
|
||||
FormattedError::prepareFormatter($this->errorFormatter, $debug)
|
||||
);
|
||||
|
||||
// While we know that there were errors initially, they might have been discarded
|
||||
if ($handledErrors !== []) {
|
||||
$result['errors'] = $handledErrors;
|
||||
}
|
||||
}
|
||||
|
||||
if (null !== $this->data) {
|
||||
if ($this->data !== null) {
|
||||
$result['data'] = $this->data;
|
||||
}
|
||||
|
||||
if (!empty($this->extensions)) {
|
||||
$result['extensions'] = (array) $this->extensions;
|
||||
|
||||
if (count($this->extensions ?? []) > 0) {
|
||||
$result['extensions'] = $this->extensions;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Part of \JsonSerializable interface
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
}
|
||||
+102
-1315
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor;
|
||||
|
||||
use GraphQL\Executor\Promise\Promise;
|
||||
|
||||
interface ExecutorImplementation
|
||||
{
|
||||
/**
|
||||
* Returns promise of {@link ExecutionResult}. Promise should always resolve, never reject.
|
||||
*/
|
||||
public function doExecute() : Promise;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise\Adapter;
|
||||
|
||||
use Amp\Deferred;
|
||||
use Amp\Failure;
|
||||
use Amp\Promise as AmpPromise;
|
||||
use Amp\Success;
|
||||
use GraphQL\Executor\Promise\Promise;
|
||||
use GraphQL\Executor\Promise\PromiseAdapter;
|
||||
use Throwable;
|
||||
use function Amp\Promise\all;
|
||||
use function array_replace;
|
||||
|
||||
class AmpPromiseAdapter implements PromiseAdapter
|
||||
{
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function isThenable($value) : bool
|
||||
{
|
||||
return $value instanceof AmpPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function convertThenable($thenable) : Promise
|
||||
{
|
||||
return new Promise($thenable, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null) : Promise
|
||||
{
|
||||
$deferred = new Deferred();
|
||||
$onResolve = static function (?Throwable $reason, $value) use ($onFulfilled, $onRejected, $deferred) : void {
|
||||
if ($reason === null && $onFulfilled !== null) {
|
||||
self::resolveWithCallable($deferred, $onFulfilled, $value);
|
||||
} elseif ($reason === null) {
|
||||
$deferred->resolve($value);
|
||||
} elseif ($onRejected !== null) {
|
||||
self::resolveWithCallable($deferred, $onRejected, $reason);
|
||||
} else {
|
||||
$deferred->fail($reason);
|
||||
}
|
||||
};
|
||||
|
||||
/** @var AmpPromise $adoptedPromise */
|
||||
$adoptedPromise = $promise->adoptedPromise;
|
||||
$adoptedPromise->onResolve($onResolve);
|
||||
|
||||
return new Promise($deferred->promise(), $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function create(callable $resolver) : Promise
|
||||
{
|
||||
$deferred = new Deferred();
|
||||
|
||||
$resolver(
|
||||
static function ($value) use ($deferred) : void {
|
||||
$deferred->resolve($value);
|
||||
},
|
||||
static function (Throwable $exception) use ($deferred) : void {
|
||||
$deferred->fail($exception);
|
||||
}
|
||||
);
|
||||
|
||||
return new Promise($deferred->promise(), $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function createFulfilled($value = null) : Promise
|
||||
{
|
||||
$promise = new Success($value);
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function createRejected($reason) : Promise
|
||||
{
|
||||
$promise = new Failure($reason);
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function all(array $promisesOrValues) : Promise
|
||||
{
|
||||
/** @var AmpPromise[] $promises */
|
||||
$promises = [];
|
||||
foreach ($promisesOrValues as $key => $item) {
|
||||
if ($item instanceof Promise) {
|
||||
$promises[$key] = $item->adoptedPromise;
|
||||
} elseif ($item instanceof AmpPromise) {
|
||||
$promises[$key] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
$deferred = new Deferred();
|
||||
|
||||
$onResolve = static function (?Throwable $reason, ?array $values) use ($promisesOrValues, $deferred) : void {
|
||||
if ($reason === null) {
|
||||
$deferred->resolve(array_replace($promisesOrValues, $values));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$deferred->fail($reason);
|
||||
};
|
||||
|
||||
all($promises)->onResolve($onResolve);
|
||||
|
||||
return new Promise($deferred->promise(), $this);
|
||||
}
|
||||
|
||||
private static function resolveWithCallable(Deferred $deferred, callable $callback, $argument) : void
|
||||
{
|
||||
try {
|
||||
$result = $callback($argument);
|
||||
} catch (Throwable $exception) {
|
||||
$deferred->fail($exception);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($result instanceof Promise) {
|
||||
$result = $result->adoptedPromise;
|
||||
}
|
||||
|
||||
$deferred->resolve($result);
|
||||
}
|
||||
}
|
||||
+22
-8
@@ -1,4 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise\Adapter;
|
||||
|
||||
use GraphQL\Executor\Promise\Promise;
|
||||
@@ -6,6 +9,9 @@ use GraphQL\Executor\Promise\PromiseAdapter;
|
||||
use GraphQL\Utils\Utils;
|
||||
use React\Promise\Promise as ReactPromise;
|
||||
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
|
||||
{
|
||||
@@ -28,10 +34,11 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
/**
|
||||
* @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;
|
||||
|
||||
return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this);
|
||||
}
|
||||
|
||||
@@ -41,6 +48,7 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
public function create(callable $resolver)
|
||||
{
|
||||
$promise = new ReactPromise($resolver);
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
|
||||
@@ -49,7 +57,8 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
*/
|
||||
public function createFulfilled($value = null)
|
||||
{
|
||||
$promise = \React\Promise\resolve($value);
|
||||
$promise = resolve($value);
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
|
||||
@@ -58,7 +67,8 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
*/
|
||||
public function createRejected($reason)
|
||||
{
|
||||
$promise = \React\Promise\reject($reason);
|
||||
$promise = reject($reason);
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
|
||||
@@ -68,11 +78,14 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
public function all(array $promisesOrValues)
|
||||
{
|
||||
// TODO: rework with generators when PHP minimum required version is changed to 5.5+
|
||||
$promisesOrValues = Utils::map($promisesOrValues, function ($item) {
|
||||
return $item instanceof Promise ? $item->adoptedPromise : $item;
|
||||
});
|
||||
$promisesOrValues = Utils::map(
|
||||
$promisesOrValues,
|
||||
static function ($item) {
|
||||
return $item instanceof Promise ? $item->adoptedPromise : $item;
|
||||
}
|
||||
);
|
||||
|
||||
$promise = \React\Promise\all($promisesOrValues)->then(function($values) use ($promisesOrValues) {
|
||||
$promise = all($promisesOrValues)->then(static function ($values) use ($promisesOrValues) : array {
|
||||
$orderedResults = [];
|
||||
|
||||
foreach ($promisesOrValues as $key => $value) {
|
||||
@@ -81,6 +94,7 @@ class ReactPromiseAdapter implements PromiseAdapter
|
||||
|
||||
return $orderedResults;
|
||||
});
|
||||
|
||||
return new Promise($promise, $this);
|
||||
}
|
||||
}
|
||||
@@ -1,117 +1,188 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise\Adapter;
|
||||
|
||||
use Exception;
|
||||
use GraphQL\Utils\Utils;
|
||||
use SplQueue;
|
||||
use Throwable;
|
||||
use function is_object;
|
||||
use function method_exists;
|
||||
|
||||
/**
|
||||
* Class SyncPromise
|
||||
*
|
||||
* Simplistic (yet full-featured) implementation of Promises A+ spec for regular PHP `sync` mode
|
||||
* (using queue to defer promises execution)
|
||||
*
|
||||
* @package GraphQL\Executor\Promise\Adapter
|
||||
* Note:
|
||||
* Library users are not supposed to use SyncPromise class in their resolvers.
|
||||
* Instead they should use GraphQL\Deferred which enforces $executor callback in the constructor.
|
||||
*
|
||||
* Root SyncPromise without explicit $executor will never resolve (actually throw while trying).
|
||||
* The whole point of Deferred is to ensure it never happens and that any resolver creates
|
||||
* at least one $executor to start the promise chain.
|
||||
*/
|
||||
class SyncPromise
|
||||
{
|
||||
const PENDING = 'pending';
|
||||
const PENDING = 'pending';
|
||||
const FULFILLED = 'fulfilled';
|
||||
const REJECTED = 'rejected';
|
||||
const REJECTED = 'rejected';
|
||||
|
||||
/**
|
||||
* @var \SplQueue
|
||||
*/
|
||||
/** @var SplQueue */
|
||||
public static $queue;
|
||||
|
||||
public static function getQueue()
|
||||
{
|
||||
return self::$queue ?: self::$queue = new \SplQueue();
|
||||
}
|
||||
/** @var string */
|
||||
public $state = self::PENDING;
|
||||
|
||||
public static function runQueue()
|
||||
/** @var mixed */
|
||||
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() : void
|
||||
{
|
||||
$q = self::$queue;
|
||||
while ($q && !$q->isEmpty()) {
|
||||
while ($q !== null && ! $q->isEmpty()) {
|
||||
$task = $q->dequeue();
|
||||
$task();
|
||||
}
|
||||
}
|
||||
|
||||
public $state = self::PENDING;
|
||||
|
||||
public $result;
|
||||
|
||||
/**
|
||||
* Promises created in `then` method of this promise and awaiting for resolution of this promise
|
||||
* @var array
|
||||
* @param callable() : mixed $executor
|
||||
*/
|
||||
private $waiting = [];
|
||||
|
||||
public function reject($reason)
|
||||
public function __construct(?callable $executor = null)
|
||||
{
|
||||
if (!$reason instanceof \Exception && !$reason instanceof \Throwable) {
|
||||
throw new \Exception('SyncPromise::reject() has to be called with an instance of \Throwable');
|
||||
if ($executor === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch ($this->state) {
|
||||
case self::PENDING:
|
||||
$this->state = self::REJECTED;
|
||||
$this->result = $reason;
|
||||
$this->enqueueWaitingPromises();
|
||||
break;
|
||||
case self::REJECTED:
|
||||
if ($reason !== $this->result) {
|
||||
throw new \Exception("Cannot change rejection reason");
|
||||
}
|
||||
break;
|
||||
case self::FULFILLED:
|
||||
throw new \Exception("Cannot reject fulfilled promise");
|
||||
}
|
||||
return $this;
|
||||
self::getQueue()->enqueue(function () use ($executor) : void {
|
||||
try {
|
||||
$this->resolve($executor());
|
||||
} catch (Throwable $e) {
|
||||
$this->reject($e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function resolve($value)
|
||||
public function resolve($value) : self
|
||||
{
|
||||
switch ($this->state) {
|
||||
case self::PENDING:
|
||||
if ($value === $this) {
|
||||
throw new \Exception("Cannot resolve promise with self");
|
||||
throw new Exception('Cannot resolve promise with self');
|
||||
}
|
||||
if (is_object($value) && method_exists($value, 'then')) {
|
||||
$value->then(
|
||||
function($resolvedValue) {
|
||||
function ($resolvedValue) : void {
|
||||
$this->resolve($resolvedValue);
|
||||
},
|
||||
function($reason) {
|
||||
function ($reason) : void {
|
||||
$this->reject($reason);
|
||||
}
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->state = self::FULFILLED;
|
||||
$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");
|
||||
throw new Exception('Cannot change value of fulfilled promise');
|
||||
}
|
||||
break;
|
||||
case self::REJECTED:
|
||||
throw new \Exception("Cannot resolve rejected promise");
|
||||
throw new Exception('Cannot resolve rejected promise');
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function then(callable $onFulfilled = null, callable $onRejected = null)
|
||||
public function reject($reason) : self
|
||||
{
|
||||
if ($this->state === self::REJECTED && !$onRejected) {
|
||||
if (! $reason instanceof Throwable) {
|
||||
throw new Exception('SyncPromise::reject() has to be called with an instance of \Throwable');
|
||||
}
|
||||
|
||||
switch ($this->state) {
|
||||
case self::PENDING:
|
||||
$this->state = self::REJECTED;
|
||||
$this->result = $reason;
|
||||
$this->enqueueWaitingPromises();
|
||||
break;
|
||||
case self::REJECTED:
|
||||
if ($reason !== $this->result) {
|
||||
throw new Exception('Cannot change rejection reason');
|
||||
}
|
||||
break;
|
||||
case self::FULFILLED:
|
||||
throw new Exception('Cannot reject fulfilled promise');
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function enqueueWaitingPromises() : void
|
||||
{
|
||||
Utils::invariant(
|
||||
$this->state !== self::PENDING,
|
||||
'Cannot enqueue derived promises when parent is still pending'
|
||||
);
|
||||
|
||||
foreach ($this->waiting as $descriptor) {
|
||||
self::getQueue()->enqueue(function () use ($descriptor) : void {
|
||||
/** @var self $promise */
|
||||
[$promise, $onFulfilled, $onRejected] = $descriptor;
|
||||
|
||||
if ($this->state === self::FULFILLED) {
|
||||
try {
|
||||
$promise->resolve($onFulfilled === null ? $this->result : $onFulfilled($this->result));
|
||||
} catch (Throwable $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
} elseif ($this->state === self::REJECTED) {
|
||||
try {
|
||||
if ($onRejected === null) {
|
||||
$promise->reject($this->result);
|
||||
} else {
|
||||
$promise->resolve($onRejected($this->result));
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
$this->waiting = [];
|
||||
}
|
||||
|
||||
public static function getQueue() : SplQueue
|
||||
{
|
||||
return self::$queue ?? self::$queue = new SplQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(mixed) : mixed $onFulfilled
|
||||
* @param callable(Throwable) : mixed $onRejected
|
||||
*/
|
||||
public function then(?callable $onFulfilled = null, ?callable $onRejected = null) : self
|
||||
{
|
||||
if ($this->state === self::REJECTED && $onRejected === null) {
|
||||
return $this;
|
||||
}
|
||||
if ($this->state === self::FULFILLED && !$onFulfilled) {
|
||||
if ($this->state === self::FULFILLED && $onFulfilled === null) {
|
||||
return $this;
|
||||
}
|
||||
$tmp = new self();
|
||||
$tmp = new self();
|
||||
$this->waiting[] = [$tmp, $onFulfilled, $onRejected];
|
||||
|
||||
if ($this->state !== self::PENDING) {
|
||||
@@ -121,38 +192,11 @@ class SyncPromise
|
||||
return $tmp;
|
||||
}
|
||||
|
||||
private function enqueueWaitingPromises()
|
||||
/**
|
||||
* @param callable(Throwable) : mixed $onRejected
|
||||
*/
|
||||
public function catch(callable $onRejected) : self
|
||||
{
|
||||
Utils::invariant($this->state !== self::PENDING, 'Cannot enqueue derived promises when parent is still pending');
|
||||
|
||||
foreach ($this->waiting as $descriptor) {
|
||||
self::getQueue()->enqueue(function () use ($descriptor) {
|
||||
/** @var $promise self */
|
||||
list($promise, $onFulfilled, $onRejected) = $descriptor;
|
||||
|
||||
if ($this->state === self::FULFILLED) {
|
||||
try {
|
||||
$promise->resolve($onFulfilled ? $onFulfilled($this->result) : $this->result);
|
||||
} catch (\Exception $e) {
|
||||
$promise->reject($e);
|
||||
} catch (\Throwable $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
} else if ($this->state === self::REJECTED) {
|
||||
try {
|
||||
if ($onRejected) {
|
||||
$promise->resolve($onRejected($this->result));
|
||||
} else {
|
||||
$promise->reject($this->result);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$promise->reject($e);
|
||||
} catch (\Throwable $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
$this->waiting = [];
|
||||
return $this->then(null, $onRejected);
|
||||
}
|
||||
}
|
||||
+43
-36
@@ -1,19 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise\Adapter;
|
||||
|
||||
use GraphQL\Deferred;
|
||||
use GraphQL\Error\InvariantViolation;
|
||||
use GraphQL\Executor\ExecutionResult;
|
||||
use GraphQL\Executor\Promise\Promise;
|
||||
use GraphQL\Executor\Promise\PromiseAdapter;
|
||||
use GraphQL\Utils\Utils;
|
||||
use Throwable;
|
||||
use function count;
|
||||
|
||||
/**
|
||||
* Class SyncPromiseAdapter
|
||||
*
|
||||
* Allows changing order of field resolution even in sync environments
|
||||
* (by leveraging queue of deferreds and promises)
|
||||
*
|
||||
* @package GraphQL\Executor\Promise\Adapter
|
||||
*/
|
||||
class SyncPromiseAdapter implements PromiseAdapter
|
||||
{
|
||||
@@ -22,7 +23,7 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
*/
|
||||
public function isThenable($value)
|
||||
{
|
||||
return $value instanceof Deferred;
|
||||
return $value instanceof SyncPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,20 +31,23 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
*/
|
||||
public function convertThenable($thenable)
|
||||
{
|
||||
if (!$thenable instanceof Deferred) {
|
||||
if (! $thenable instanceof SyncPromise) {
|
||||
// End-users should always use Deferred (and don't use SyncPromise directly)
|
||||
throw new InvariantViolation('Expected instance of GraphQL\Deferred, got ' . Utils::printSafe($thenable));
|
||||
}
|
||||
return new Promise($thenable->promise, $this);
|
||||
|
||||
return new Promise($thenable, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 */
|
||||
$promise = $promise->adoptedPromise;
|
||||
return new Promise($promise->then($onFulfilled, $onRejected), $this);
|
||||
/** @var SyncPromise $adoptedPromise */
|
||||
$adoptedPromise = $promise->adoptedPromise;
|
||||
|
||||
return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,12 +59,16 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
|
||||
try {
|
||||
$resolver(
|
||||
[$promise, 'resolve'],
|
||||
[$promise, 'reject']
|
||||
[
|
||||
$promise,
|
||||
'resolve',
|
||||
],
|
||||
[
|
||||
$promise,
|
||||
'reject',
|
||||
]
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
$promise->reject($e);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (Throwable $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
|
||||
@@ -73,6 +81,7 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
public function createFulfilled($value = null)
|
||||
{
|
||||
$promise = new SyncPromise();
|
||||
|
||||
return new Promise($promise->resolve($value), $this);
|
||||
}
|
||||
|
||||
@@ -82,6 +91,7 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
public function createRejected($reason)
|
||||
{
|
||||
$promise = new SyncPromise();
|
||||
|
||||
return new Promise($promise->reject($reason), $this);
|
||||
}
|
||||
|
||||
@@ -92,20 +102,22 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
{
|
||||
$all = new SyncPromise();
|
||||
|
||||
$total = count($promisesOrValues);
|
||||
$count = 0;
|
||||
$total = count($promisesOrValues);
|
||||
$count = 0;
|
||||
$result = [];
|
||||
|
||||
foreach ($promisesOrValues as $index => $promiseOrValue) {
|
||||
if ($promiseOrValue instanceof Promise) {
|
||||
$result[$index] = null;
|
||||
$promiseOrValue->then(
|
||||
function($value) use ($index, &$count, $total, &$result, $all) {
|
||||
static function ($value) use ($index, &$count, $total, &$result, $all) : void {
|
||||
$result[$index] = $value;
|
||||
$count++;
|
||||
if ($count >= $total) {
|
||||
$all->resolve($result);
|
||||
if ($count < $total) {
|
||||
return;
|
||||
}
|
||||
|
||||
$all->resolve($result);
|
||||
},
|
||||
[$all, 'reject']
|
||||
);
|
||||
@@ -117,26 +129,23 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
if ($count === $total) {
|
||||
$all->resolve($result);
|
||||
}
|
||||
|
||||
return new Promise($all, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously wait when promise completes
|
||||
*
|
||||
* @param Promise $promise
|
||||
* @return mixed
|
||||
* @return ExecutionResult
|
||||
*/
|
||||
public function wait(Promise $promise)
|
||||
{
|
||||
$this->beforeWait($promise);
|
||||
$dfdQueue = Deferred::getQueue();
|
||||
$promiseQueue = SyncPromise::getQueue();
|
||||
$taskQueue = SyncPromise::getQueue();
|
||||
|
||||
while (
|
||||
$promise->adoptedPromise->state === SyncPromise::PENDING &&
|
||||
!($dfdQueue->isEmpty() && $promiseQueue->isEmpty())
|
||||
while ($promise->adoptedPromise->state === SyncPromise::PENDING &&
|
||||
! $taskQueue->isEmpty()
|
||||
) {
|
||||
Deferred::runQueue();
|
||||
SyncPromise::runQueue();
|
||||
$this->onWait($promise);
|
||||
}
|
||||
@@ -146,17 +155,17 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
|
||||
if ($syncPromise->state === SyncPromise::FULFILLED) {
|
||||
return $syncPromise->result;
|
||||
} else if ($syncPromise->state === SyncPromise::REJECTED) {
|
||||
}
|
||||
|
||||
if ($syncPromise->state === SyncPromise::REJECTED) {
|
||||
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
|
||||
*
|
||||
* @param Promise $promise
|
||||
*/
|
||||
protected function beforeWait(Promise $promise)
|
||||
{
|
||||
@@ -164,8 +173,6 @@ class SyncPromiseAdapter implements PromiseAdapter
|
||||
|
||||
/**
|
||||
* Execute while running promise completion
|
||||
*
|
||||
* @param Promise $promise
|
||||
*/
|
||||
protected function onWait(Promise $promise)
|
||||
{
|
||||
|
||||
+12
-11
@@ -1,38 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise;
|
||||
|
||||
use GraphQL\Executor\Promise\Adapter\SyncPromise;
|
||||
use GraphQL\Utils\Utils;
|
||||
use React\Promise\Promise as ReactPromise;
|
||||
|
||||
/**
|
||||
* Convenience wrapper for promises represented by Promise Adapter
|
||||
*/
|
||||
class Promise
|
||||
{
|
||||
private $adapter;
|
||||
|
||||
/** @var SyncPromise|ReactPromise */
|
||||
public $adoptedPromise;
|
||||
|
||||
/** @var PromiseAdapter */
|
||||
private $adapter;
|
||||
|
||||
/**
|
||||
* Promise constructor.
|
||||
*
|
||||
* @param mixed $adoptedPromise
|
||||
* @param 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 ' . self::class);
|
||||
|
||||
$this->adapter = $adapter;
|
||||
$this->adapter = $adapter;
|
||||
$this->adoptedPromise = $adoptedPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|null $onFulfilled
|
||||
* @param callable|null $onRejected
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor\Promise;
|
||||
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Provides a means for integration of async PHP platforms ([related docs](data-fetching.md#async-php))
|
||||
*/
|
||||
@@ -9,18 +14,22 @@ interface PromiseAdapter
|
||||
/**
|
||||
* Return true if the value is a promise or a deferred of the underlying platform
|
||||
*
|
||||
* @api
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function isThenable($value);
|
||||
|
||||
/**
|
||||
* Converts thenable of the underlying platform into GraphQL\Executor\Promise\Promise instance
|
||||
*
|
||||
* @api
|
||||
* @param object $thenable
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function convertThenable($thenable);
|
||||
|
||||
@@ -28,14 +37,11 @@ interface PromiseAdapter
|
||||
* Accepts our Promise wrapper, extracts adopted promise out of it and executes actual `then` logic described
|
||||
* in Promises/A+ specs. Then returns new wrapped instance of GraphQL\Executor\Promise\Promise.
|
||||
*
|
||||
* @api
|
||||
* @param Promise $promise
|
||||
* @param callable|null $onFulfilled
|
||||
* @param callable|null $onRejected
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
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
|
||||
@@ -43,18 +49,20 @@ interface PromiseAdapter
|
||||
* Expected resolver signature:
|
||||
* function(callable $resolve, callable $reject)
|
||||
*
|
||||
* @api
|
||||
* @param callable $resolver
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function create(callable $resolver);
|
||||
|
||||
/**
|
||||
* Creates a fulfilled Promise for a value if the value is not a promise.
|
||||
*
|
||||
* @api
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function createFulfilled($value = null);
|
||||
|
||||
@@ -62,9 +70,11 @@ interface PromiseAdapter
|
||||
* Creates a rejected promise for a reason if the reason is not a promise. If
|
||||
* the provided reason is a promise, then it is returned as-is.
|
||||
*
|
||||
* @api
|
||||
* @param \Throwable $reason
|
||||
* @param Throwable $reason
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function createRejected($reason);
|
||||
|
||||
@@ -72,9 +82,11 @@ interface PromiseAdapter
|
||||
* Given an array of promises (or values), returns a promise that is fulfilled when all the
|
||||
* items in the array are fulfilled.
|
||||
*
|
||||
* @api
|
||||
* @param array $promisesOrValues Promises or values.
|
||||
* @param Promise[]|mixed[] $promisesOrValues Promises or values.
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function all(array $promisesOrValues);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+255
-306
@@ -1,33 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GraphQL\Executor;
|
||||
|
||||
|
||||
use GraphQL\Error\Error;
|
||||
use GraphQL\Error\InvariantViolation;
|
||||
use GraphQL\Language\AST\ArgumentNode;
|
||||
use GraphQL\Language\AST\BooleanValueNode;
|
||||
use GraphQL\Language\AST\DirectiveNode;
|
||||
use GraphQL\Language\AST\EnumValueDefinitionNode;
|
||||
use GraphQL\Language\AST\EnumValueNode;
|
||||
use GraphQL\Language\AST\FieldDefinitionNode;
|
||||
use GraphQL\Language\AST\FieldNode;
|
||||
use GraphQL\Language\AST\FloatValueNode;
|
||||
use GraphQL\Language\AST\FragmentSpreadNode;
|
||||
use GraphQL\Language\AST\InlineFragmentNode;
|
||||
use GraphQL\Language\AST\IntValueNode;
|
||||
use GraphQL\Language\AST\ListValueNode;
|
||||
use GraphQL\Language\AST\Node;
|
||||
use GraphQL\Language\AST\NodeList;
|
||||
use GraphQL\Language\AST\VariableNode;
|
||||
use GraphQL\Language\AST\NullValueNode;
|
||||
use GraphQL\Language\AST\ObjectValueNode;
|
||||
use GraphQL\Language\AST\StringValueNode;
|
||||
use GraphQL\Language\AST\ValueNode;
|
||||
use GraphQL\Language\AST\VariableDefinitionNode;
|
||||
use GraphQL\Language\AST\VariableNode;
|
||||
use GraphQL\Language\Printer;
|
||||
use GraphQL\Type\Schema;
|
||||
use GraphQL\Type\Definition\Directive;
|
||||
use GraphQL\Type\Definition\EnumType;
|
||||
use GraphQL\Type\Definition\FieldDefinition;
|
||||
use GraphQL\Type\Definition\InputObjectType;
|
||||
use GraphQL\Type\Definition\InputType;
|
||||
use GraphQL\Type\Definition\LeafType;
|
||||
use GraphQL\Type\Definition\ListOfType;
|
||||
use GraphQL\Type\Definition\NonNull;
|
||||
use GraphQL\Type\Definition\ScalarType;
|
||||
use GraphQL\Type\Definition\Type;
|
||||
use GraphQL\Type\Schema;
|
||||
use GraphQL\Utils\AST;
|
||||
use GraphQL\Utils\TypeInfo;
|
||||
use GraphQL\Utils\Utils;
|
||||
use GraphQL\Validator\DocumentValidator;
|
||||
use GraphQL\Utils\Value;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
use function array_key_exists;
|
||||
use function array_map;
|
||||
use function count;
|
||||
use function sprintf;
|
||||
|
||||
class Values
|
||||
{
|
||||
@@ -36,134 +54,94 @@ class Values
|
||||
* variable definitions and arbitrary input. If the input cannot be coerced
|
||||
* to match the variable definitions, a Error will be thrown.
|
||||
*
|
||||
* @param Schema $schema
|
||||
* @param VariableDefinitionNode[] $definitionNodes
|
||||
* @param array $inputs
|
||||
* @return array
|
||||
* @throws Error
|
||||
*/
|
||||
public static function getVariableValues(Schema $schema, $definitionNodes, array $inputs)
|
||||
{
|
||||
$coercedValues = [];
|
||||
foreach ($definitionNodes as $definitionNode) {
|
||||
$varName = $definitionNode->variable->name->value;
|
||||
$varType = TypeInfo::typeFromAST($schema, $definitionNode->type);
|
||||
|
||||
if (!Type::isInputType($varType)) {
|
||||
throw new Error(
|
||||
'Variable "$'.$varName.'" expected value of type ' .
|
||||
'"' . Printer::doPrint($definitionNode->type) . '" which cannot be used as an input type.',
|
||||
[$definitionNode->type]
|
||||
);
|
||||
}
|
||||
|
||||
if (!array_key_exists($varName, $inputs)) {
|
||||
$defaultValue = $definitionNode->defaultValue;
|
||||
if ($defaultValue) {
|
||||
$coercedValues[$varName] = AST::valueFromAST($defaultValue, $varType);
|
||||
}
|
||||
if ($varType instanceof NonNull) {
|
||||
throw new Error(
|
||||
'Variable "$'.$varName .'" of required type ' .
|
||||
'"'. Utils::printSafe($varType) . '" was not provided.',
|
||||
[$definitionNode]
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$value = $inputs[$varName];
|
||||
$errors = self::isValidPHPValue($value, $varType);
|
||||
if (!empty($errors)) {
|
||||
$message = "\n" . implode("\n", $errors);
|
||||
throw new Error(
|
||||
'Variable "$' . $varName . '" got invalid value ' .
|
||||
json_encode($value) . '.' . $message,
|
||||
[$definitionNode]
|
||||
);
|
||||
}
|
||||
|
||||
$coercedValue = self::coerceValue($varType, $value);
|
||||
Utils::invariant($coercedValue !== Utils::undefined(), 'Should have reported error.');
|
||||
$coercedValues[$varName] = $coercedValue;
|
||||
}
|
||||
}
|
||||
return $coercedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares an object map of argument values given a list of argument
|
||||
* definitions and list of argument AST nodes.
|
||||
* @param VariableDefinitionNode[] $varDefNodes
|
||||
* @param mixed[] $inputs
|
||||
*
|
||||
* @param FieldDefinition|Directive $def
|
||||
* @param FieldNode|\GraphQL\Language\AST\DirectiveNode $node
|
||||
* @param $variableValues
|
||||
* @return array
|
||||
* @throws Error
|
||||
* @return mixed[]
|
||||
*/
|
||||
public static function getArgumentValues($def, $node, $variableValues = null)
|
||||
public static function getVariableValues(Schema $schema, $varDefNodes, array $inputs)
|
||||
{
|
||||
$argDefs = $def->args;
|
||||
$argNodes = $node->arguments;
|
||||
|
||||
if (!$argDefs || null === $argNodes) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$errors = [];
|
||||
$coercedValues = [];
|
||||
$undefined = Utils::undefined();
|
||||
foreach ($varDefNodes as $varDefNode) {
|
||||
$varName = $varDefNode->variable->name->value;
|
||||
/** @var InputType|Type $varType */
|
||||
$varType = TypeInfo::typeFromAST($schema, $varDefNode->type);
|
||||
|
||||
/** @var ArgumentNode[] $argNodeMap */
|
||||
$argNodeMap = $argNodes ? Utils::keyMap($argNodes, function (ArgumentNode $arg) {
|
||||
return $arg->name->value;
|
||||
}) : [];
|
||||
|
||||
foreach ($argDefs as $argDef) {
|
||||
$name = $argDef->name;
|
||||
$argType = $argDef->getType();
|
||||
$argumentNode = isset($argNodeMap[$name]) ? $argNodeMap[$name] : null;
|
||||
|
||||
if (!$argumentNode) {
|
||||
if ($argDef->defaultValueExists()) {
|
||||
$coercedValues[$name] = $argDef->defaultValue;
|
||||
} else if ($argType instanceof NonNull) {
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" of required type ' .
|
||||
'"' . Utils::printSafe($argType) . '" was not provided.',
|
||||
[$node]
|
||||
);
|
||||
}
|
||||
} else if ($argumentNode->value instanceof VariableNode) {
|
||||
$variableName = $argumentNode->value->name->value;
|
||||
|
||||
if ($variableValues && array_key_exists($variableName, $variableValues)) {
|
||||
// Note: this does not check that this variable value is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
$coercedValues[$name] = $variableValues[$variableName];
|
||||
} else if ($argDef->defaultValueExists()) {
|
||||
$coercedValues[$name] = $argDef->defaultValue;
|
||||
} else if ($argType instanceof NonNull) {
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" of required type "' . Utils::printSafe($argType) . '" was ' .
|
||||
'provided the variable "$' . $variableName . '" which was not provided ' .
|
||||
'a runtime value.',
|
||||
[ $argumentNode->value ]
|
||||
);
|
||||
}
|
||||
if (! Type::isInputType($varType)) {
|
||||
// Must use input types for variables. This should be caught during
|
||||
// validation, however is checked again here for safety.
|
||||
$errors[] = new Error(
|
||||
sprintf(
|
||||
'Variable "$%s" expected value of type "%s" which cannot be used as an input type.',
|
||||
$varName,
|
||||
Printer::doPrint($varDefNode->type)
|
||||
),
|
||||
[$varDefNode->type]
|
||||
);
|
||||
} else {
|
||||
$valueNode = $argumentNode->value;
|
||||
$coercedValue = AST::valueFromAST($valueNode, $argType, $variableValues);
|
||||
if ($coercedValue === $undefined) {
|
||||
$errors = DocumentValidator::isValidLiteralValue($argType, $valueNode);
|
||||
$message = !empty($errors) ? ("\n" . implode("\n", $errors)) : '';
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" got invalid value ' . Printer::doPrint($valueNode) . '.' . $message,
|
||||
[ $argumentNode->value ]
|
||||
$hasValue = array_key_exists($varName, $inputs);
|
||||
$value = $hasValue ? $inputs[$varName] : Utils::undefined();
|
||||
|
||||
if (! $hasValue && ($varDefNode->defaultValue !== null)) {
|
||||
// If no value was provided to a variable with a default value,
|
||||
// use the default value.
|
||||
$coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType);
|
||||
} elseif ((! $hasValue || $value === null) && ($varType instanceof NonNull)) {
|
||||
// If no value or a nullish value was provided to a variable with a
|
||||
// non-null type (required), produce an error.
|
||||
$errors[] = new Error(
|
||||
sprintf(
|
||||
$hasValue
|
||||
? 'Variable "$%s" of non-null type "%s" must not be null.'
|
||||
: 'Variable "$%s" of required type "%s" was not provided.',
|
||||
$varName,
|
||||
Utils::printSafe($varType)
|
||||
),
|
||||
[$varDefNode]
|
||||
);
|
||||
} elseif ($hasValue) {
|
||||
if ($value === null) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
$coercedValues[$varName] = null;
|
||||
} else {
|
||||
// Otherwise, a non-null value was provided, coerce it to the expected
|
||||
// type or report an error if coercion fails.
|
||||
$coerced = Value::coerceValue($value, $varType, $varDefNode);
|
||||
/** @var Error[] $coercionErrors */
|
||||
$coercionErrors = $coerced['errors'];
|
||||
if (count($coercionErrors ?? []) > 0) {
|
||||
$messagePrelude = sprintf(
|
||||
'Variable "$%s" got invalid value %s; ',
|
||||
$varName,
|
||||
Utils::printSafeJson($value)
|
||||
);
|
||||
|
||||
foreach ($coercionErrors as $error) {
|
||||
$errors[] = new Error(
|
||||
$messagePrelude . $error->getMessage(),
|
||||
$error->getNodes(),
|
||||
$error->getSource(),
|
||||
$error->getPositions(),
|
||||
$error->getPath(),
|
||||
$error->getPrevious(),
|
||||
$error->getExtensions()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$coercedValues[$varName] = $coerced['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
$coercedValues[$name] = $coercedValue;
|
||||
}
|
||||
}
|
||||
return $coercedValues;
|
||||
|
||||
if (count($errors) > 0) {
|
||||
return [$errors, null];
|
||||
}
|
||||
|
||||
return [null, $coercedValues];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,213 +151,184 @@ class 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
|
||||
* @param FragmentSpreadNode|FieldNode|InlineFragmentNode|EnumValueDefinitionNode|FieldDefinitionNode $node
|
||||
* @param mixed[]|null $variableValues
|
||||
*
|
||||
* @return array|null
|
||||
* @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;
|
||||
});
|
||||
$directiveNode = Utils::find(
|
||||
$node->directives,
|
||||
static function (DirectiveNode $directive) use ($directiveDef) : bool {
|
||||
return $directive->name->value === $directiveDef->name;
|
||||
}
|
||||
);
|
||||
|
||||
if ($directiveNode) {
|
||||
if ($directiveNode !== null) {
|
||||
return self::getArgumentValues($directiveDef, $directiveNode, $variableValues);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares an object map of argument values given a list of argument
|
||||
* definitions and list of argument AST nodes.
|
||||
*
|
||||
* @param FieldDefinition|Directive $def
|
||||
* @param FieldNode|DirectiveNode $node
|
||||
* @param mixed[] $variableValues
|
||||
*
|
||||
* @return mixed[]
|
||||
*
|
||||
* @throws Error
|
||||
*/
|
||||
public static function getArgumentValues($def, $node, $variableValues = null)
|
||||
{
|
||||
if (count($def->args) === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$argumentNodes = $node->arguments;
|
||||
$argumentValueMap = [];
|
||||
foreach ($argumentNodes as $argumentNode) {
|
||||
$argumentValueMap[$argumentNode->name->value] = $argumentNode->value;
|
||||
}
|
||||
|
||||
return static::getArgumentValuesForMap($def, $argumentValueMap, $variableValues, $node);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param FieldDefinition|Directive $fieldDefinition
|
||||
* @param ArgumentNode[] $argumentValueMap
|
||||
* @param mixed[] $variableValues
|
||||
* @param Node|null $referenceNode
|
||||
*
|
||||
* @return mixed[]
|
||||
*
|
||||
* @throws Error
|
||||
*/
|
||||
public static function getArgumentValuesForMap($fieldDefinition, $argumentValueMap, $variableValues = null, $referenceNode = null)
|
||||
{
|
||||
$argumentDefinitions = $fieldDefinition->args;
|
||||
$coercedValues = [];
|
||||
|
||||
foreach ($argumentDefinitions as $argumentDefinition) {
|
||||
$name = $argumentDefinition->name;
|
||||
$argType = $argumentDefinition->getType();
|
||||
$argumentValueNode = $argumentValueMap[$name] ?? null;
|
||||
|
||||
if ($argumentValueNode instanceof VariableNode) {
|
||||
$variableName = $argumentValueNode->name->value;
|
||||
$hasValue = array_key_exists($variableName, $variableValues ?? []);
|
||||
$isNull = $hasValue ? $variableValues[$variableName] === null : false;
|
||||
} else {
|
||||
$hasValue = $argumentValueNode !== null;
|
||||
$isNull = $argumentValueNode instanceof NullValueNode;
|
||||
}
|
||||
|
||||
if (! $hasValue && $argumentDefinition->defaultValueExists()) {
|
||||
// If no argument was provided where the definition has a default value,
|
||||
// use the default value.
|
||||
$coercedValues[$name] = $argumentDefinition->defaultValue;
|
||||
} elseif ((! $hasValue || $isNull) && ($argType instanceof NonNull)) {
|
||||
// If no argument or a null value was provided to an argument with a
|
||||
// non-null type (required), produce a field error.
|
||||
if ($isNull) {
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" of non-null type ' .
|
||||
'"' . Utils::printSafe($argType) . '" must not be null.',
|
||||
$referenceNode
|
||||
);
|
||||
}
|
||||
|
||||
if ($argumentValueNode instanceof VariableNode) {
|
||||
$variableName = $argumentValueNode->name->value;
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" of required type "' . Utils::printSafe($argType) . '" was ' .
|
||||
'provided the variable "$' . $variableName . '" which was not provided ' .
|
||||
'a runtime value.',
|
||||
[$argumentValueNode]
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" of required type ' .
|
||||
'"' . Utils::printSafe($argType) . '" was not provided.',
|
||||
$referenceNode
|
||||
);
|
||||
} elseif ($hasValue) {
|
||||
if ($argumentValueNode instanceof NullValueNode) {
|
||||
// If the explicit value `null` was provided, an entry in the coerced
|
||||
// values must exist as the value `null`.
|
||||
$coercedValues[$name] = null;
|
||||
} elseif ($argumentValueNode instanceof VariableNode) {
|
||||
$variableName = $argumentValueNode->name->value;
|
||||
Utils::invariant($variableValues !== null, 'Must exist for hasValue to be true.');
|
||||
// Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
$coercedValues[$name] = $variableValues[$variableName] ?? null;
|
||||
} else {
|
||||
$valueNode = $argumentValueNode;
|
||||
$coercedValue = AST::valueFromAST($valueNode, $argType, $variableValues);
|
||||
if (Utils::isInvalid($coercedValue)) {
|
||||
// Note: ValuesOfCorrectType validation should catch this before
|
||||
// execution. This is a runtime check to ensure execution does not
|
||||
// continue with an invalid argument value.
|
||||
throw new Error(
|
||||
'Argument "' . $name . '" has invalid value ' . Printer::doPrint($valueNode) . '.',
|
||||
[$argumentValueNode]
|
||||
);
|
||||
}
|
||||
$coercedValues[$name] = $coercedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $coercedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated as of 8.0 (Moved to \GraphQL\Utils\AST::valueFromAST)
|
||||
*
|
||||
* @param $valueNode
|
||||
* @param InputType $type
|
||||
* @param null $variables
|
||||
* @return array|null|\stdClass
|
||||
* @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $valueNode
|
||||
* @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type
|
||||
* @param mixed[]|null $variables
|
||||
*
|
||||
* @return mixed[]|stdClass|null
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function valueFromAST($valueNode, InputType $type, $variables = null)
|
||||
public static function valueFromAST(ValueNode $valueNode, InputType $type, ?array $variables = null)
|
||||
{
|
||||
return AST::valueFromAST($valueNode, $type, $variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a PHP value and a GraphQL type, determine if the value will be
|
||||
* accepted for that type. This is primarily useful for validating the
|
||||
* runtime values of query variables.
|
||||
* @deprecated as of 0.12 (Use coerceValue() directly for richer information)
|
||||
*
|
||||
* @param $value
|
||||
* @param InputType $type
|
||||
* @return array
|
||||
* @param mixed[] $value
|
||||
* @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function isValidPHPValue($value, InputType $type)
|
||||
{
|
||||
// A value must be provided if the type is non-null.
|
||||
if ($type instanceof NonNull) {
|
||||
if (null === $value) {
|
||||
return ['Expected "' . Utils::printSafe($type) . '", found null.'];
|
||||
}
|
||||
return self::isValidPHPValue($value, $type->getWrappedType());
|
||||
}
|
||||
$errors = Value::coerceValue($value, $type)['errors'];
|
||||
|
||||
if (null === $value) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Lists accept a non-list value as a list of one.
|
||||
if ($type instanceof ListOfType) {
|
||||
$itemType = $type->getWrappedType();
|
||||
if (is_array($value)) {
|
||||
$tmp = [];
|
||||
foreach ($value as $index => $item) {
|
||||
$errors = self::isValidPHPValue($item, $itemType);
|
||||
$tmp = array_merge($tmp, Utils::map($errors, function ($error) use ($index) {
|
||||
return "In element #$index: $error";
|
||||
}));
|
||||
}
|
||||
return $tmp;
|
||||
}
|
||||
return self::isValidPHPValue($value, $itemType);
|
||||
}
|
||||
|
||||
// Input objects check each defined field.
|
||||
if ($type instanceof InputObjectType) {
|
||||
if (!is_object($value) && !is_array($value)) {
|
||||
return ["Expected \"{$type->name}\", found not an object."];
|
||||
}
|
||||
$fields = $type->getFields();
|
||||
$errors = [];
|
||||
|
||||
// Ensure every provided field is defined.
|
||||
$props = is_object($value) ? get_object_vars($value) : $value;
|
||||
foreach ($props as $providedField => $tmp) {
|
||||
if (!isset($fields[$providedField])) {
|
||||
$errors[] = "In field \"{$providedField}\": Unknown field.";
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every defined field is valid.
|
||||
foreach ($fields as $fieldName => $tmp) {
|
||||
$newErrors = self::isValidPHPValue(isset($value[$fieldName]) ? $value[$fieldName] : null, $fields[$fieldName]->getType());
|
||||
$errors = array_merge(
|
||||
$errors,
|
||||
Utils::map($newErrors, function ($error) use ($fieldName) {
|
||||
return "In field \"{$fieldName}\": {$error}";
|
||||
})
|
||||
);
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
if ($type instanceof LeafType) {
|
||||
try {
|
||||
// Scalar/Enum input checks to ensure the type can parse the value to
|
||||
// a non-null value.
|
||||
$parseResult = $type->parseValue($value);
|
||||
if (null === $parseResult && !$type->isValidValue($value)) {
|
||||
$v = Utils::printSafeJson($value);
|
||||
return [
|
||||
"Expected type \"{$type->name}\", found $v."
|
||||
];
|
||||
}
|
||||
return [];
|
||||
} catch (\Exception $e) {
|
||||
return [
|
||||
"Expected type \"{$type->name}\", found " . Utils::printSafeJson($value) . ': ' .
|
||||
$e->getMessage()
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
return [
|
||||
"Expected type \"{$type->name}\", found " . Utils::printSafeJson($value) . ': ' .
|
||||
$e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvariantViolation('Must be input type');
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a type and any value, return a runtime value coerced to match the type.
|
||||
*/
|
||||
private static function coerceValue(Type $type, $value)
|
||||
{
|
||||
$undefined = Utils::undefined();
|
||||
if ($value === $undefined) {
|
||||
return $undefined;
|
||||
}
|
||||
|
||||
if ($type instanceof NonNull) {
|
||||
if ($value === null) {
|
||||
// Intentionally return no value.
|
||||
return $undefined;
|
||||
}
|
||||
return self::coerceValue($type->getWrappedType(), $value);
|
||||
}
|
||||
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($type instanceof ListOfType) {
|
||||
$itemType = $type->getWrappedType();
|
||||
if (is_array($value) || $value instanceof \Traversable) {
|
||||
$coercedValues = [];
|
||||
foreach ($value as $item) {
|
||||
$itemValue = self::coerceValue($itemType, $item);
|
||||
if ($undefined === $itemValue) {
|
||||
// Intentionally return no value.
|
||||
return $undefined;
|
||||
}
|
||||
$coercedValues[] = $itemValue;
|
||||
}
|
||||
return $coercedValues;
|
||||
} else {
|
||||
$coercedValue = self::coerceValue($itemType, $value);
|
||||
if ($coercedValue === $undefined) {
|
||||
// Intentionally return no value.
|
||||
return $undefined;
|
||||
}
|
||||
return [$coercedValue];
|
||||
}
|
||||
}
|
||||
|
||||
if ($type instanceof InputObjectType) {
|
||||
$coercedObj = [];
|
||||
$fields = $type->getFields();
|
||||
foreach ($fields as $fieldName => $field) {
|
||||
if (!array_key_exists($fieldName, $value)) {
|
||||
if ($field->defaultValueExists()) {
|
||||
$coercedObj[$fieldName] = $field->defaultValue;
|
||||
} else if ($field->getType() instanceof NonNull) {
|
||||
// Intentionally return no value.
|
||||
return $undefined;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$fieldValue = self::coerceValue($field->getType(), $value[$fieldName]);
|
||||
if ($fieldValue === $undefined) {
|
||||
// Intentionally return no value.
|
||||
return $undefined;
|
||||
}
|
||||
$coercedObj[$fieldName] = $fieldValue;
|
||||
}
|
||||
return $coercedObj;
|
||||
}
|
||||
|
||||
if ($type instanceof LeafType) {
|
||||
$parsed = $type->parseValue($value);
|
||||
if (null === $parsed) {
|
||||
// null or invalid values represent a failure to parse correctly,
|
||||
// in which case no value is returned.
|
||||
return $undefined;
|
||||
}
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
throw new InvariantViolation('Must be input type');
|
||||
return $errors
|
||||
? array_map(
|
||||
static function (Throwable $error) : string {
|
||||
return $error->getMessage();
|
||||
},
|
||||
$errors
|
||||
)
|
||||
: [];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user