Version 4.6.0

This commit is contained in:
Neo committed 2025-12-19 05:55:31 -08:00
1 parent f79dcf067a
commit 517a5e1f70
2036 files changed
+110041 -26162

No files matched your search

+12 -47
View File
@@ -1,61 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL;
use GraphQL\Executor\Promise\Adapter\SyncPromise;
class Deferred
class Deferred extends SyncPromise
{
/**
* @var \SplQueue
* @param callable() : mixed $executor
*/
private static $queue;
public static function create(callable $executor) : self
{
return new self($executor);
}
/**
* @var callable
* @param callable() : mixed $executor
*/
private $callback;
/**
* @var SyncPromise
*/
public $promise;
public static function getQueue()
public function __construct(callable $executor)
{
return self::$queue ?: self::$queue = new \SplQueue();
}
public static function runQueue()
{
$q = self::$queue;
while ($q && !$q->isEmpty()) {
/** @var self $dfd */
$dfd = $q->dequeue();
$dfd->run();
}
}
public function __construct(callable $callback)
{
$this->callback = $callback;
$this->promise = new SyncPromise();
self::getQueue()->enqueue($this);
}
public function then($onFulfilled = null, $onRejected = null)
{
return $this->promise->then($onFulfilled, $onRejected);
}
private function run()
{
try {
$cb = $this->callback;
$this->promise->resolve($cb());
} catch (\Exception $e) {
$this->promise->reject($e);
} catch (\Throwable $e) {
$this->promise->reject($e);
}
parent::__construct($executor);
}
}
-18
View File
@@ -1,18 +0,0 @@
<?php
namespace GraphQL;
trigger_error(
'GraphQL\Error was moved to GraphQL\Error\Error and will be deleted on next release',
E_USER_DEPRECATED
);
/**
* Class Error
*
* @deprecated as of 8.0 in favor of GraphQL\Error\Error
* @package GraphQL
*/
class Error extends \GraphQL\Error\Error
{
}
+7 -2
View File
@@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
/**
@@ -14,8 +17,9 @@ interface ClientAware
/**
* Returns true when exception message is safe to be displayed to a client.
*
* @api
* @return bool
*
* @api
*/
public function isClientSafe();
@@ -24,8 +28,9 @@ interface ClientAware
*
* Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.
*
* @api
* @return string
*
* @api
*/
public function getCategory();
}
-12
View File
@@ -1,12 +0,0 @@
<?php
namespace GraphQL\Error;
/**
* Collection of flags for [error debugging](error-handling.md#debugging-tools).
*/
class Debug
{
const INCLUDE_DEBUG_MESSAGE = 1;
const INCLUDE_TRACE = 2;
const RETHROW_INTERNAL_EXCEPTIONS = 4;
}
+17
View File
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
/**
* Collection of flags for [error debugging](error-handling.md#debugging-tools).
*/
final class DebugFlag
{
public const NONE = 0;
public const INCLUDE_DEBUG_MESSAGE = 1;
public const INCLUDE_TRACE = 2;
public const RETHROW_INTERNAL_EXCEPTIONS = 4;
public const RETHROW_UNSAFE_EXCEPTIONS = 8;
}
+194 -112
View File
@@ -1,9 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use Exception;
use GraphQL\Language\AST\Node;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
use GraphQL\Utils\Utils;
use JsonSerializable;
use Throwable;
use Traversable;
use function array_filter;
use function array_map;
use function array_values;
use function count;
use function is_array;
use function iterator_to_array;
/**
* Describes an Error found during the parse, validate, or
@@ -19,19 +33,14 @@ use GraphQL\Utils\Utils;
* Class extends standard PHP `\Exception`, so all standard methods of base `\Exception` class
* are available in addition to those listed below.
*/
class Error extends \Exception implements \JsonSerializable, ClientAware
class Error extends Exception implements JsonSerializable, ClientAware
{
const CATEGORY_GRAPHQL = 'graphql';
const CATEGORY_GRAPHQL = 'graphql';
const CATEGORY_INTERNAL = 'internal';
/**
* A message describing the Error for debugging purposes.
* Lazily initialized.
*
* @var string
*/
public $message;
/**
* @var SourceLocation[]
*/
private $locations;
@@ -40,135 +49,148 @@ class Error extends \Exception implements \JsonSerializable, ClientAware
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* @var array
* @var mixed[]|null
*/
public $path;
/**
* An array of GraphQL AST Nodes corresponding to this error.
*
* @var array
* @var Node[]|null
*/
public $nodes;
/**
* The source GraphQL document corresponding to this error.
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*
* @var Source|null
*/
private $source;
/**
* @var array
*/
/** @var int[] */
private $positions;
/**
* @var bool
*/
/** @var bool */
private $isClientSafe;
/**
* @var string
*/
/** @var string */
protected $category;
/** @var mixed[]|null */
protected $extensions;
/**
* @param string $message
* @param Node|Node[]|Traversable|null $nodes
* @param mixed[] $positions
* @param mixed[]|null $path
* @param Throwable $previous
* @param mixed[] $extensions
*/
public function __construct(
$message = '',
$nodes = null,
?Source $source = null,
array $positions = [],
$path = null,
$previous = null,
array $extensions = []
) {
parent::__construct($message, 0, $previous);
// Compute list of blame nodes.
if ($nodes instanceof Traversable) {
$nodes = iterator_to_array($nodes);
} elseif ($nodes !== null && ! is_array($nodes)) {
$nodes = [$nodes];
}
$this->nodes = $nodes;
$this->source = $source;
$this->positions = $positions;
$this->path = $path;
$this->extensions = count($extensions) > 0 ? $extensions : (
$previous instanceof self
? $previous->extensions
: []
);
if ($previous instanceof ClientAware) {
$this->isClientSafe = $previous->isClientSafe();
$cat = $previous->getCategory();
$this->category = $cat === '' || $cat === null ? self::CATEGORY_INTERNAL: $cat;
} elseif ($previous !== null) {
$this->isClientSafe = false;
$this->category = self::CATEGORY_INTERNAL;
} else {
$this->isClientSafe = true;
$this->category = self::CATEGORY_GRAPHQL;
}
}
/**
* Given an arbitrary Error, presumably thrown while attempting to execute a
* GraphQL operation, produce a new GraphQLError aware of the location in the
* document responsible for the original Error.
*
* @param $error
* @param array|null $nodes
* @param array|null $path
* @param mixed $error
* @param Node[]|null $nodes
* @param mixed[]|null $path
*
* @return Error
*/
public static function createLocatedError($error, $nodes = null, $path = null)
{
if ($error instanceof self) {
if ($error->path && $error->nodes) {
if ($error->path !== null && $error->nodes !== null && count($error->nodes) !== 0) {
return $error;
} else {
$nodes = $nodes ?: $error->nodes;
$path = $path ?: $error->path;
}
$nodes = $nodes ?? $error->nodes;
$path = $path ?? $error->path;
}
$source = $positions = $originalError = null;
$source = null;
$originalError = null;
$positions = [];
$extensions = [];
if ($error instanceof self) {
$message = $error->getMessage();
$message = $error->getMessage();
$originalError = $error;
$nodes = $error->nodes ?: $nodes;
$source = $error->source;
$positions = $error->positions;
} else if ($error instanceof \Exception || $error instanceof \Throwable) {
$message = $error->getMessage();
$nodes = $error->nodes ?? $nodes;
$source = $error->source;
$positions = $error->positions;
$extensions = $error->extensions;
} elseif ($error instanceof Throwable) {
$message = $error->getMessage();
$originalError = $error;
} else {
$message = (string) $error;
}
return new static(
$message ?: 'An unknown error occurred.',
$message === '' || $message === null ? 'An unknown error occurred.' : $message,
$nodes,
$source,
$positions,
$path,
$originalError
$originalError,
$extensions
);
}
/**
* @param Error $error
* @return array
* @return mixed[]
*/
public static function formatError(Error $error)
{
return $error->toSerializableArray();
}
/**
* @param string $message
* @param array|null $nodes
* @param Source $source
* @param array|null $positions
* @param array|null $path
* @param \Throwable $previous
*/
public function __construct(
$message,
$nodes = null,
Source $source = null,
$positions = null,
$path = null,
$previous = null
)
{
parent::__construct($message, 0, $previous);
if ($nodes instanceof \Traversable) {
$nodes = iterator_to_array($nodes);
}
$this->nodes = $nodes;
$this->source = $source;
$this->positions = $positions;
$this->path = $path;
if ($previous instanceof ClientAware) {
$this->isClientSafe = $previous->isClientSafe();
$this->category = $previous->getCategory() ?: static::CATEGORY_INTERNAL;
} else if ($previous) {
$this->isClientSafe = false;
$this->category = static::CATEGORY_INTERNAL;
} else {
$this->isClientSafe = true;
$this->category = static::CATEGORY_GRAPHQL;
}
}
/**
* @inheritdoc
*/
@@ -185,34 +207,40 @@ class Error extends \Exception implements \JsonSerializable, ClientAware
return $this->category;
}
/**
* @return Source|null
*/
public function getSource()
public function getSource() : ?Source
{
if (null === $this->source) {
if (!empty($this->nodes[0]) && !empty($this->nodes[0]->loc)) {
if ($this->source === null) {
if (isset($this->nodes[0]) && $this->nodes[0]->loc !== null) {
$this->source = $this->nodes[0]->loc->source;
}
}
return $this->source;
}
/**
* @return array
* @return int[]
*/
public function getPositions()
public function getPositions() : array
{
if (null === $this->positions) {
if (!empty($this->nodes)) {
$positions = array_map(function($node) {
if (count($this->positions) === 0 && count($this->nodes ?? []) > 0) {
$positions = array_map(
static function ($node) : ?int {
return isset($node->loc) ? $node->loc->start : null;
}, $this->nodes);
$this->positions = array_filter($positions, function($p) {
},
$this->nodes
);
$positions = array_filter(
$positions,
static function ($p) : bool {
return $p !== null;
});
}
}
);
$this->positions = array_values($positions);
}
return $this->positions;
}
@@ -227,19 +255,38 @@ class Error extends \Exception implements \JsonSerializable, ClientAware
* point out to field mentioned in multiple fragments. Errors during execution include a
* single location, the field which produced the error.
*
* @api
* @return SourceLocation[]
*
* @api
*/
public function getLocations()
public function getLocations() : array
{
if (null === $this->locations) {
if (! isset($this->locations)) {
$positions = $this->getPositions();
$source = $this->getSource();
$source = $this->getSource();
$nodes = $this->nodes;
if ($positions && $source) {
$this->locations = array_map(function ($pos) use ($source) {
return $source->getLocation($pos);
}, $positions);
if ($source !== null && count($positions) !== 0) {
$this->locations = array_map(
static function ($pos) use ($source) : SourceLocation {
return $source->getLocation($pos);
},
$positions
);
} elseif ($nodes !== null && count($nodes) !== 0) {
$locations = array_filter(
array_map(
static function ($node) : ?SourceLocation {
if (isset($node->loc->source)) {
return $node->loc->source->getLocation($node->loc->start);
}
return null;
},
$nodes
)
);
$this->locations = array_values($locations);
} else {
$this->locations = [];
}
@@ -248,53 +295,88 @@ class Error extends \Exception implements \JsonSerializable, ClientAware
return $this->locations;
}
/**
* @return Node[]|null
*/
public function getNodes()
{
return $this->nodes;
}
/**
* Returns an array describing the path from the root value to the field which produced this error.
* Only included for execution errors.
*
* @return mixed[]|null
*
* @api
* @return array|null
*/
public function getPath()
{
return $this->path;
}
/**
* @return mixed[]
*/
public function getExtensions()
{
return $this->extensions;
}
/**
* Returns array representation of error suitable for serialization
*
* @deprecated Use FormattedError::createFromException() instead
* @return array
*
* @return mixed[]
*
* @codeCoverageIgnore
*/
public function toSerializableArray()
{
$arr = [
'message' => $this->getMessage()
'message' => $this->getMessage(),
];
$locations = Utils::map($this->getLocations(), function(SourceLocation $loc) {
return $loc->toSerializableArray();
});
$locations = Utils::map(
$this->getLocations(),
static function (SourceLocation $loc) : array {
return $loc->toSerializableArray();
}
);
if (!empty($locations)) {
if (count($locations) > 0) {
$arr['locations'] = $locations;
}
if (!empty($this->path)) {
if (count($this->path ?? []) > 0) {
$arr['path'] = $this->path;
}
if (count($this->extensions ?? []) > 0) {
$arr['extensions'] = $this->extensions;
}
return $arr;
}
/**
* Specify data which should be serialized to JSON
*
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
*
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
function jsonSerialize()
public function jsonSerialize()
{
return $this->toSerializableArray();
}
/**
* @return string
*/
public function __toString()
{
return FormattedError::printError($this);
}
}
+244 -104
View File
@@ -1,10 +1,38 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use Countable;
use ErrorException;
use GraphQL\Language\AST\Node;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\WrappingType;
use GraphQL\Utils\Utils;
use Throwable;
use function addcslashes;
use function array_filter;
use function array_intersect_key;
use function array_map;
use function array_merge;
use function array_shift;
use function count;
use function get_class;
use function gettype;
use function implode;
use function is_array;
use function is_bool;
use function is_object;
use function is_scalar;
use function is_string;
use function mb_strlen;
use function preg_split;
use function sprintf;
use function str_repeat;
use function strlen;
/**
* This class is used for [default error formatting](error-handling.md).
@@ -13,20 +41,119 @@ use GraphQL\Utils\Utils;
*/
class FormattedError
{
/** @var string */
private static $internalErrorMessage = 'Internal server error';
/**
* Set default error message for internal errors formatted using createFormattedError().
* This value can be overridden by passing 3rd argument to `createFormattedError()`.
*
* @api
* @param string $msg
*
* @api
*/
public static function setInternalErrorMessage($msg)
{
self::$internalErrorMessage = $msg;
}
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*
* @return string
*/
public static function printError(Error $error)
{
$printedLocations = [];
if (count($error->nodes ?? []) !== 0) {
/** @var Node $node */
foreach ($error->nodes as $node) {
if ($node->loc === null) {
continue;
}
if ($node->loc->source === null) {
continue;
}
$printedLocations[] = self::highlightSourceAtLocation(
$node->loc->source,
$node->loc->source->getLocation($node->loc->start)
);
}
} elseif ($error->getSource() !== null && count($error->getLocations()) !== 0) {
$source = $error->getSource();
foreach (($error->getLocations() ?? []) as $location) {
$printedLocations[] = self::highlightSourceAtLocation($source, $location);
}
}
return count($printedLocations) === 0
? $error->getMessage()
: implode("\n\n", array_merge([$error->getMessage()], $printedLocations)) . "\n";
}
/**
* Render a helpful description of the location of the error in the GraphQL
* Source document.
*
* @return string
*/
private static function highlightSourceAtLocation(Source $source, SourceLocation $location)
{
$line = $location->line;
$lineOffset = $source->locationOffset->line - 1;
$columnOffset = self::getColumnOffset($source, $location);
$contextLine = $line + $lineOffset;
$contextColumn = $location->column + $columnOffset;
$prevLineNum = (string) ($contextLine - 1);
$lineNum = (string) $contextLine;
$nextLineNum = (string) ($contextLine + 1);
$padLen = strlen($nextLineNum);
$lines = preg_split('/\r\n|[\n\r]/', $source->body);
$lines[0] = self::whitespace($source->locationOffset->column - 1) . $lines[0];
$outputLines = [
sprintf('%s (%s:%s)', $source->name, $contextLine, $contextColumn),
$line >= 2 ? (self::lpad($padLen, $prevLineNum) . ': ' . $lines[$line - 2]) : null,
self::lpad($padLen, $lineNum) . ': ' . $lines[$line - 1],
self::whitespace(2 + $padLen + $contextColumn - 1) . '^',
$line < count($lines) ? self::lpad($padLen, $nextLineNum) . ': ' . $lines[$line] : null,
];
return implode("\n", array_filter($outputLines));
}
/**
* @return int
*/
private static function getColumnOffset(Source $source, SourceLocation $location)
{
return $location->line === 1 ? $source->locationOffset->column - 1 : 0;
}
/**
* @param int $len
*
* @return string
*/
private static function whitespace($len)
{
return str_repeat(' ', $len);
}
/**
* @param int $len
*
* @return string
*/
private static function lpad($len, $str)
{
return self::whitespace($len - mb_strlen($str)) . $str;
}
/**
* Standard GraphQL error formatter. Converts any exception to array
* conforming to GraphQL spec.
@@ -34,52 +161,57 @@ class FormattedError
* This method only exposes exception message when exception implements ClientAware interface
* (or when debug flags are passed).
*
* For a list of available debug flags see GraphQL\Error\Debug constants.
* For a list of available debug flags @see \GraphQL\Error\DebugFlag constants.
*
* @param string $internalErrorMessage
*
* @return mixed[]
*
* @throws Throwable
*
* @api
* @param \Throwable $e
* @param bool|int $debug
* @param string $internalErrorMessage
* @return array
* @throws \Throwable
*/
public static function createFromException($e, $debug = false, $internalErrorMessage = null)
public static function createFromException(Throwable $exception, int $debug = DebugFlag::NONE, $internalErrorMessage = null) : array
{
Utils::invariant(
$e instanceof \Exception || $e instanceof \Throwable,
"Expected exception, got %s",
Utils::getVariableType($e)
);
$internalErrorMessage = $internalErrorMessage ?? self::$internalErrorMessage;
$internalErrorMessage = $internalErrorMessage ?: self::$internalErrorMessage;
if ($e instanceof ClientAware) {
if ($exception instanceof ClientAware) {
$formattedError = [
'message' => $e->isClientSafe() ? $e->getMessage() : $internalErrorMessage,
'category' => $e->getCategory()
'message' => $exception->isClientSafe() ? $exception->getMessage() : $internalErrorMessage,
'extensions' => [
'category' => $exception->getCategory(),
],
];
} else {
$formattedError = [
'message' => $internalErrorMessage,
'category' => Error::CATEGORY_INTERNAL
'message' => $internalErrorMessage,
'extensions' => [
'category' => Error::CATEGORY_INTERNAL,
],
];
}
if ($e instanceof Error) {
$locations = Utils::map($e->getLocations(), function(SourceLocation $loc) {
return $loc->toSerializableArray();
});
if (!empty($locations)) {
if ($exception instanceof Error) {
$locations = Utils::map(
$exception->getLocations(),
static function (SourceLocation $loc) : array {
return $loc->toSerializableArray();
}
);
if (count($locations) > 0) {
$formattedError['locations'] = $locations;
}
if (!empty($e->path)) {
$formattedError['path'] = $e->path;
if (count($exception->path ?? []) > 0) {
$formattedError['path'] = $exception->path;
}
if (count($exception->getExtensions() ?? []) > 0) {
$formattedError['extensions'] = $exception->getExtensions() + $formattedError['extensions'];
}
}
if ($debug) {
$formattedError = self::addDebugEntries($formattedError, $e, $debug);
if ($debug !== DebugFlag::NONE) {
$formattedError = self::addDebugEntries($formattedError, $exception, $debug);
}
return $formattedError;
@@ -87,126 +219,125 @@ class FormattedError
/**
* Decorates spec-compliant $formattedError with debug entries according to $debug flags
* (see GraphQL\Error\Debug for available flags)
* (@see \GraphQL\Error\DebugFlag for available flags)
*
* @param array $formattedError
* @param \Throwable $e
* @param bool $debug
* @return array
* @throws \Throwable
* @param mixed[] $formattedError
*
* @return mixed[]
*
* @throws Throwable
*/
public static function addDebugEntries(array $formattedError, $e, $debug)
public static function addDebugEntries(array $formattedError, Throwable $e, int $debugFlag) : array
{
if (!$debug) {
if ($debugFlag === DebugFlag::NONE) {
return $formattedError;
}
Utils::invariant(
$e instanceof \Exception || $e instanceof \Throwable,
"Expected exception, got %s",
Utils::getVariableType($e)
);
$debug = (int) $debug;
if ($debug & Debug::RETHROW_INTERNAL_EXCEPTIONS) {
if (!$e instanceof Error) {
if (( $debugFlag & DebugFlag::RETHROW_INTERNAL_EXCEPTIONS) !== 0) {
if (! $e instanceof Error) {
throw $e;
} else if ($e->getPrevious()) {
}
if ($e->getPrevious() !== null) {
throw $e->getPrevious();
}
}
$isInternal = !$e instanceof ClientAware || !$e->isClientSafe();
$isUnsafe = ! $e instanceof ClientAware || ! $e->isClientSafe();
if (($debug & Debug::INCLUDE_DEBUG_MESSAGE) && $isInternal) {
if (($debugFlag & DebugFlag::RETHROW_UNSAFE_EXCEPTIONS) !== 0 && $isUnsafe && $e->getPrevious() !== null) {
throw $e->getPrevious();
}
if (($debugFlag & DebugFlag::INCLUDE_DEBUG_MESSAGE) !== 0 && $isUnsafe) {
// Displaying debugMessage as a first entry:
$formattedError = ['debugMessage' => $e->getMessage()] + $formattedError;
}
if ($debug & Debug::INCLUDE_TRACE) {
if ($e instanceof \ErrorException || $e instanceof \Error) {
if (($debugFlag & DebugFlag::INCLUDE_TRACE) !== 0) {
if ($e instanceof ErrorException || $e instanceof \Error) {
$formattedError += [
'file' => $e->getFile(),
'line' => $e->getLine(),
];
}
$isTrivial = $e instanceof Error && !$e->getPrevious();
$isTrivial = $e instanceof Error && $e->getPrevious() === null;
if (!$isTrivial) {
$debugging = $e->getPrevious() ?: $e;
if (! $isTrivial) {
$debugging = $e->getPrevious() ?? $e;
$formattedError['trace'] = static::toSafeTrace($debugging);
}
}
return $formattedError;
}
/**
* Prepares final error formatter taking in account $debug flags.
* If initial formatter is not set, FormattedError::createFromException is used
*
* @param callable|null $formatter
* @param $debug
* @return callable|\Closure
*/
public static function prepareFormatter(callable $formatter = null, $debug)
public static function prepareFormatter(?callable $formatter, int $debug) : callable
{
$formatter = $formatter ?: function($e) {
$formatter = $formatter ?? static function ($e) : array {
return FormattedError::createFromException($e);
};
if ($debug) {
$formatter = function($e) use ($formatter, $debug) {
if ($debug !== DebugFlag::NONE) {
$formatter = static function ($e) use ($formatter, $debug) : array {
return FormattedError::addDebugEntries($formatter($e), $e, $debug);
};
}
return $formatter;
}
/**
* Returns error trace as serializable array
*
* @param Throwable $error
*
* @return mixed[]
*
* @api
* @param \Throwable $error
* @return array
*/
public static function toSafeTrace($error)
{
$trace = $error->getTrace();
// Remove invariant entries as they don't provide much value:
if (
isset($trace[0]['function']) && isset($trace[0]['class']) &&
('GraphQL\Utils\Utils::invariant' === $trace[0]['class'].'::'.$trace[0]['function'])) {
if (isset($trace[0]['function']) && isset($trace[0]['class']) &&
// Remove invariant entries as they don't provide much value:
($trace[0]['class'] . '::' . $trace[0]['function'] === 'GraphQL\Utils\Utils::invariant')) {
array_shift($trace);
} elseif (! isset($trace[0]['file'])) {
// Remove root call as it's likely error handler trace:
array_shift($trace);
}
// Remove root call as it's likely error handler trace:
else if (!isset($trace[0]['file'])) {
array_shift($trace);
}
return array_map(
static function ($err) : array {
$safeErr = array_intersect_key($err, ['file' => true, 'line' => true]);
return array_map(function($err) {
$safeErr = array_intersect_key($err, ['file' => true, 'line' => true]);
if (isset($err['function'])) {
$func = $err['function'];
$args = array_map([self::class, 'printVar'], $err['args'] ?? []);
$funcStr = $func . '(' . implode(', ', $args) . ')';
if (isset($err['function'])) {
$func = $err['function'];
$args = !empty($err['args']) ? array_map([__CLASS__, 'printVar'], $err['args']) : [];
$funcStr = $func . '(' . implode(", ", $args) . ')';
if (isset($err['class'])) {
$safeErr['call'] = $err['class'] . '::' . $funcStr;
} else {
$safeErr['function'] = $funcStr;
if (isset($err['class'])) {
$safeErr['call'] = $err['class'] . '::' . $funcStr;
} else {
$safeErr['function'] = $funcStr;
}
}
}
return $safeErr;
}, $trace);
return $safeErr;
},
$trace
);
}
/**
* @param $var
* @param mixed $var
*
* @return string
*/
public static function printVar($var)
@@ -216,16 +347,17 @@ class FormattedError
if ($var instanceof WrappingType) {
$var = $var->getWrappedType(true);
}
return 'GraphQLType: ' . $var->name;
}
if (is_object($var)) {
return 'instance of ' . get_class($var) . ($var instanceof \Countable ? '(' . count($var) . ')' : '');
return 'instance of ' . get_class($var) . ($var instanceof Countable ? '(' . count($var) . ')' : '');
}
if (is_array($var)) {
return 'array(' . count($var) . ')';
}
if ('' === $var) {
if ($var === '') {
return '(empty string)';
}
if (is_string($var)) {
@@ -237,42 +369,50 @@ class FormattedError
if (is_scalar($var)) {
return $var;
}
if (null === $var) {
if ($var === null) {
return 'null';
}
return gettype($var);
}
/**
* @deprecated as of v0.8.0
* @param $error
*
* @param string $error
* @param SourceLocation[] $locations
* @return array
*
* @return mixed[]
*/
public static function create($error, array $locations = [])
{
$formatted = [
'message' => $error
];
$formatted = ['message' => $error];
if (!empty($locations)) {
$formatted['locations'] = array_map(function($loc) { return $loc->toArray();}, $locations);
if (count($locations) > 0) {
$formatted['locations'] = array_map(
static function ($loc) : array {
return $loc->toArray();
},
$locations
);
}
return $formatted;
}
/**
* @param \ErrorException $e
* @deprecated as of v0.10.0, use general purpose method createFromException() instead
* @return array
*
* @return mixed[]
*
* @codeCoverageIgnore
*/
public static function createFromPHPError(\ErrorException $e)
public static function createFromPHPError(ErrorException $e)
{
return [
'message' => $e->getMessage(),
'message' => $e->getMessage(),
'severity' => $e->getSeverity(),
'trace' => self::toSafeTrace($e)
'trace' => self::toSafeTrace($e),
];
}
}
+10 -5
View File
@@ -1,15 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use LogicException;
/**
* Class InvariantVoilation
*
* Note:
* This exception should not inherit base Error exception as it is raised when there is an error somewhere in
* user-land code
*
* @package GraphQL\Error
*/
class InvariantViolation extends \LogicException
class InvariantViolation extends LogicException
{
public static function shouldNotHappen() : self
{
return new self('This should not have happened');
}
}
+11 -57
View File
@@ -1,71 +1,25 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
use function sprintf;
class SyntaxError extends Error
{
/**
* @param Source $source
* @param int $position
* @param int $position
* @param string $description
*/
public function __construct(Source $source, $position, $description)
{
$location = $source->getLocation($position);
$line = $location->line + $source->locationOffset->line - 1;
$columnOffset = self::getColumnOffset($source, $location);
$column = $location->column + $columnOffset;
$syntaxError =
"Syntax Error {$source->name} ({$line}:{$column}) $description\n" .
"\n".
self::highlightSourceAtLocation($source, $location);
parent::__construct($syntaxError, null, $source, [$position]);
parent::__construct(
sprintf('Syntax Error: %s', $description),
null,
$source,
[$position]
);
}
/**
* @param Source $source
* @param SourceLocation $location
* @return string
*/
public static function highlightSourceAtLocation(Source $source, SourceLocation $location)
{
$line = $location->line;
$lineOffset = $source->locationOffset->line - 1;
$columnOffset = self::getColumnOffset($source, $location);
$contextLine = $line + $lineOffset;
$prevLineNum = (string) ($contextLine - 1);
$lineNum = (string) $contextLine;
$nextLineNum = (string) ($contextLine + 1);
$padLen = mb_strlen($nextLineNum, 'UTF-8');
$unicodeChars = json_decode('"\u2028\u2029"'); // Quick hack to get js-compatible representation of these chars
$lines = preg_split('/\r\n|[\n\r' . $unicodeChars . ']/su', $source->body);
$whitespace = function ($len) {
return str_repeat(' ', $len);
};
$lpad = function ($len, $str) {
return str_pad($str, $len - mb_strlen($str, 'UTF-8') + 1, ' ', STR_PAD_LEFT);
};
$lines[0] = $whitespace($source->locationOffset->column - 1) . $lines[0];
return
($line >= 2 ? $lpad($padLen, $prevLineNum) . ': ' . $lines[$line - 2] . "\n" : '') .
($lpad($padLen, $lineNum) . ': ' . $lines[$line - 1] . "\n") .
($whitespace(2 + $padLen + $location->column - 1 + $columnOffset) . "^\n") .
($line < count($lines) ? $lpad($padLen, $nextLineNum) . ': ' . $lines[$line] . "\n" : '');
}
public static function getColumnOffset(Source $source, SourceLocation $location)
{
return $location->line === 1 ? $source->locationOffset->column - 1 : 0;
}
}
+6 -5
View File
@@ -1,14 +1,15 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use RuntimeException;
/**
* Class UserError
*
* Error caused by actions of GraphQL clients. Can be safely displayed to a client...
*
* @package GraphQL\Error
*/
class UserError extends \RuntimeException implements ClientAware
class UserError extends RuntimeException implements ClientAware
{
/**
* @return bool
+50 -33
View File
@@ -1,6 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Error;
use GraphQL\Exception\InvalidArgument;
use function is_int;
use function trigger_error;
use const E_USER_WARNING;
/**
* Encapsulates warnings produced by the library.
*
@@ -9,28 +17,29 @@ namespace GraphQL\Error;
*/
final class Warning
{
const WARNING_NAME = 1;
const WARNING_ASSIGN = 2;
const WARNING_CONFIG = 4;
const WARNING_FULL_SCHEMA_SCAN = 8;
const WARNING_CONFIG_DEPRECATION = 16;
const WARNING_NOT_A_TYPE = 32;
const ALL = 63;
public const WARNING_ASSIGN = 2;
public const WARNING_CONFIG = 4;
public const WARNING_FULL_SCHEMA_SCAN = 8;
public const WARNING_CONFIG_DEPRECATION = 16;
public const WARNING_NOT_A_TYPE = 32;
public const ALL = 63;
static $enableWarnings = self::ALL;
/** @var int */
private static $enableWarnings = self::ALL;
static $warned = [];
/** @var mixed[] */
private static $warned = [];
static private $warningHandler;
/** @var callable|null */
private static $warningHandler;
/**
* Sets warning handler which can intercept all system warnings.
* When not set, trigger_error() is used to notify about warnings.
*
* @api
* @param callable|null $warningHandler
*/
public static function setWarningHandler(callable $warningHandler = null)
public static function setWarningHandler(?callable $warningHandler = null)
{
self::$warningHandler = $warningHandler;
}
@@ -43,18 +52,20 @@ final class Warning
*
* When passing true - suppresses all warnings.
*
* @api
* @param bool|int $suppress
*
* @api
*/
static function suppress($suppress = true)
public static function suppress($suppress = true)
{
if (true === $suppress) {
if ($suppress === true) {
self::$enableWarnings = 0;
} else if (false === $suppress) {
} elseif ($suppress === false) {
self::$enableWarnings = self::ALL;
} else {
$suppress = (int) $suppress;
} elseif (is_int($suppress)) {
self::$enableWarnings &= ~$suppress;
} else {
throw InvalidArgument::fromExpectedTypeAndArgument('bool|int', $suppress);
}
}
@@ -66,39 +77,45 @@ final class Warning
*
* When passing true - re-enables all warnings.
*
* @api
* @param bool|int $enable
*
* @api
*/
public static function enable($enable = true)
{
if (true === $enable) {
if ($enable === true) {
self::$enableWarnings = self::ALL;
} else if (false === $enable) {
} elseif ($enable === false) {
self::$enableWarnings = 0;
} else {
$enable = (int) $enable;
} elseif (is_int($enable)) {
self::$enableWarnings |= $enable;
} else {
throw InvalidArgument::fromExpectedTypeAndArgument('bool|int', $enable);
}
}
static function warnOnce($errorMessage, $warningId, $messageLevel = null)
public static function warnOnce(string $errorMessage, int $warningId, ?int $messageLevel = null)
{
if (self::$warningHandler) {
$messageLevel = $messageLevel ?? E_USER_WARNING;
if (self::$warningHandler !== null) {
$fn = self::$warningHandler;
$fn($errorMessage, $warningId);
} else if ((self::$enableWarnings & $warningId) > 0 && !isset(self::$warned[$warningId])) {
$fn($errorMessage, $warningId, $messageLevel);
} elseif ((self::$enableWarnings & $warningId) > 0 && ! isset(self::$warned[$warningId])) {
self::$warned[$warningId] = true;
trigger_error($errorMessage, $messageLevel ?: E_USER_WARNING);
trigger_error($errorMessage, $messageLevel);
}
}
static function warn($errorMessage, $warningId, $messageLevel = null)
public static function warn(string $errorMessage, int $warningId, ?int $messageLevel = null)
{
if (self::$warningHandler) {
$messageLevel = $messageLevel ?? E_USER_WARNING;
if (self::$warningHandler !== null) {
$fn = self::$warningHandler;
$fn($errorMessage, $warningId);
} else if ((self::$enableWarnings & $warningId) > 0) {
trigger_error($errorMessage, $messageLevel ?: E_USER_WARNING);
$fn($errorMessage, $warningId, $messageLevel);
} elseif ((self::$enableWarnings & $warningId) > 0) {
trigger_error($errorMessage, $messageLevel);
}
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Exception;
use InvalidArgumentException;
use function gettype;
use function sprintf;
final class InvalidArgument extends InvalidArgumentException
{
/**
* @param mixed $argument
*/
public static function fromExpectedTypeAndArgument(string $expectedType, $argument) : self
{
return new self(sprintf('Expected type "%s", got "%s"', $expectedType, gettype($argument)));
}
}
+29 -38
View File
@@ -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
View File
@@ -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();
}
}
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);
}
}
@@ -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);
}
}
@@ -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
View File
@@ -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
View File
@@ -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
)
: [];
}
}
@@ -0,0 +1,282 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use Generator;
use GraphQL\Error\Error;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\DefinitionNode;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\EnumValueNode;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\FloatValueNode;
use GraphQL\Language\AST\FragmentDefinitionNode;
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\NullValueNode;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Language\AST\VariableNode;
use GraphQL\Type\Definition\AbstractType;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use function count;
use function sprintf;
/**
* @internal
*/
class Collector
{
/** @var Schema */
private $schema;
/** @var Runtime */
private $runtime;
/** @var OperationDefinitionNode|null */
public $operation = null;
/** @var FragmentDefinitionNode[] */
public $fragments = [];
/** @var ObjectType|null */
public $rootType;
/** @var FieldNode[][] */
private $fields;
/** @var array<string, bool> */
private $visitedFragments;
public function __construct(Schema $schema, Runtime $runtime)
{
$this->schema = $schema;
$this->runtime = $runtime;
}
public function initialize(DocumentNode $documentNode, ?string $operationName = null)
{
$hasMultipleAssumedOperations = false;
foreach ($documentNode->definitions as $definitionNode) {
/** @var DefinitionNode|Node $definitionNode */
if ($definitionNode instanceof OperationDefinitionNode) {
if ($operationName === null && $this->operation !== null) {
$hasMultipleAssumedOperations = true;
}
if ($operationName === null ||
(isset($definitionNode->name) && $definitionNode->name->value === $operationName)
) {
$this->operation = $definitionNode;
}
} elseif ($definitionNode instanceof FragmentDefinitionNode) {
$this->fragments[$definitionNode->name->value] = $definitionNode;
}
}
if ($this->operation === null) {
if ($operationName !== null) {
$this->runtime->addError(new Error(sprintf('Unknown operation named "%s".', $operationName)));
} else {
$this->runtime->addError(new Error('Must provide an operation.'));
}
return;
}
if ($hasMultipleAssumedOperations) {
$this->runtime->addError(new Error('Must provide operation name if query contains multiple operations.'));
return;
}
if ($this->operation->operation === 'query') {
$this->rootType = $this->schema->getQueryType();
} elseif ($this->operation->operation === 'mutation') {
$this->rootType = $this->schema->getMutationType();
} elseif ($this->operation->operation === 'subscription') {
$this->rootType = $this->schema->getSubscriptionType();
} else {
$this->runtime->addError(new Error(sprintf('Cannot initialize collector with operation type "%s".', $this->operation->operation)));
}
}
/**
* @return Generator
*/
public function collectFields(ObjectType $runtimeType, ?SelectionSetNode $selectionSet)
{
$this->fields = [];
$this->visitedFragments = [];
$this->doCollectFields($runtimeType, $selectionSet);
foreach ($this->fields as $resultName => $fieldNodes) {
$fieldNode = $fieldNodes[0];
$fieldName = $fieldNode->name->value;
$argumentValueMap = null;
if (count($fieldNode->arguments) > 0) {
foreach ($fieldNode->arguments as $argumentNode) {
$argumentValueMap = $argumentValueMap ?? [];
$argumentValueMap[$argumentNode->name->value] = $argumentNode->value;
}
}
if ($fieldName !== Introspection::TYPE_NAME_FIELD_NAME &&
! ($runtimeType === $this->schema->getQueryType() && ($fieldName === Introspection::SCHEMA_FIELD_NAME || $fieldName === Introspection::TYPE_FIELD_NAME)) &&
! $runtimeType->hasField($fieldName)
) {
// do not emit error
continue;
}
yield new CoroutineContextShared($fieldNodes, $fieldName, $resultName, $argumentValueMap);
}
}
private function doCollectFields(ObjectType $runtimeType, ?SelectionSetNode $selectionSet)
{
if ($selectionSet === null) {
return;
}
foreach ($selectionSet->selections as $selection) {
/** @var FieldNode|FragmentSpreadNode|InlineFragmentNode $selection */
if (count($selection->directives) > 0) {
foreach ($selection->directives as $directiveNode) {
if ($directiveNode->name->value === Directive::SKIP_NAME) {
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $condition */
$condition = null;
foreach ($directiveNode->arguments as $argumentNode) {
if ($argumentNode->name->value === Directive::IF_ARGUMENT_NAME) {
$condition = $argumentNode->value;
break;
}
}
if ($condition === null) {
$this->runtime->addError(new Error(
sprintf('@%s directive is missing "%s" argument.', Directive::SKIP_NAME, Directive::IF_ARGUMENT_NAME),
$selection
));
} else {
if ($this->runtime->evaluate($condition, Type::boolean()) === true) {
continue 2; // !!! advances outer loop
}
}
} elseif ($directiveNode->name->value === Directive::INCLUDE_NAME) {
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $condition */
$condition = null;
foreach ($directiveNode->arguments as $argumentNode) {
if ($argumentNode->name->value === Directive::IF_ARGUMENT_NAME) {
$condition = $argumentNode->value;
break;
}
}
if ($condition === null) {
$this->runtime->addError(new Error(
sprintf('@%s directive is missing "%s" argument.', Directive::INCLUDE_NAME, Directive::IF_ARGUMENT_NAME),
$selection
));
} else {
if ($this->runtime->evaluate($condition, Type::boolean()) !== true) {
continue 2; // !!! advances outer loop
}
}
}
}
}
if ($selection instanceof FieldNode) {
$resultName = $selection->alias === null ? $selection->name->value : $selection->alias->value;
if (! isset($this->fields[$resultName])) {
$this->fields[$resultName] = [];
}
$this->fields[$resultName][] = $selection;
} elseif ($selection instanceof FragmentSpreadNode) {
$fragmentName = $selection->name->value;
if (isset($this->visitedFragments[$fragmentName])) {
continue;
}
if (! isset($this->fragments[$fragmentName])) {
$this->runtime->addError(new Error(
sprintf('Fragment "%s" does not exist.', $fragmentName),
$selection
));
continue;
}
$this->visitedFragments[$fragmentName] = true;
$fragmentDefinition = $this->fragments[$fragmentName];
$conditionTypeName = $fragmentDefinition->typeCondition->name->value;
if (! $this->schema->hasType($conditionTypeName)) {
$this->runtime->addError(new Error(
sprintf('Cannot spread fragment "%s", type "%s" does not exist.', $fragmentName, $conditionTypeName),
$selection
));
continue;
}
$conditionType = $this->schema->getType($conditionTypeName);
if ($conditionType instanceof ObjectType) {
if ($runtimeType->name !== $conditionType->name) {
continue;
}
} elseif ($conditionType instanceof AbstractType) {
if (! $this->schema->isSubType($conditionType, $runtimeType)) {
continue;
}
}
$this->doCollectFields($runtimeType, $fragmentDefinition->selectionSet);
} elseif ($selection instanceof InlineFragmentNode) {
if ($selection->typeCondition !== null) {
$conditionTypeName = $selection->typeCondition->name->value;
if (! $this->schema->hasType($conditionTypeName)) {
$this->runtime->addError(new Error(
sprintf('Cannot spread inline fragment, type "%s" does not exist.', $conditionTypeName),
$selection
));
continue;
}
$conditionType = $this->schema->getType($conditionTypeName);
if ($conditionType instanceof ObjectType) {
if ($runtimeType->name !== $conditionType->name) {
continue;
}
} elseif ($conditionType instanceof AbstractType) {
if (! $this->schema->isSubType($conditionType, $runtimeType)) {
continue;
}
}
}
$this->doCollectFields($runtimeType, $selection->selectionSet);
}
}
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
/**
* @internal
*/
class CoroutineContext
{
/** @var CoroutineContextShared */
public $shared;
/** @var ObjectType */
public $type;
/** @var mixed */
public $value;
/** @var object */
public $result;
/** @var string[] */
public $path;
/** @var ResolveInfo */
public $resolveInfo;
/** @var string[]|null */
public $nullFence;
/**
* @param mixed $value
* @param object $result
* @param string[] $path
* @param string[]|null $nullFence
*/
public function __construct(
CoroutineContextShared $shared,
ObjectType $type,
$value,
$result,
array $path,
?array $nullFence = null
) {
$this->shared = $shared;
$this->type = $type;
$this->value = $value;
$this->result = $result;
$this->path = $path;
$this->nullFence = $nullFence;
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\ValueNode;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
/**
* @internal
*/
class CoroutineContextShared
{
/** @var FieldNode[] */
public $fieldNodes;
/** @var string */
public $fieldName;
/** @var string */
public $resultName;
/** @var ValueNode[]|null */
public $argumentValueMap;
/** @var SelectionSetNode|null */
public $mergedSelectionSet;
/** @var ObjectType|null */
public $typeGuard1;
/** @var callable|null */
public $resolveIfType1;
/** @var mixed */
public $argumentsIfType1;
/** @var ResolveInfo|null */
public $resolveInfoIfType1;
/** @var ObjectType|null */
public $typeGuard2;
/** @var CoroutineContext[]|null */
public $childContextsIfType2;
/**
* @param FieldNode[] $fieldNodes
* @param mixed[]|null $argumentValueMap
*/
public function __construct(array $fieldNodes, string $fieldName, string $resultName, ?array $argumentValueMap)
{
$this->fieldNodes = $fieldNodes;
$this->fieldName = $fieldName;
$this->resultName = $resultName;
$this->argumentValueMap = $argumentValueMap;
}
}
@@ -0,0 +1,970 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use Generator;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Error\Warning;
use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\ExecutorImplementation;
use GraphQL\Executor\Promise\Promise;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Executor\Values;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\ValueNode;
use GraphQL\Type\Definition\AbstractType;
use GraphQL\Type\Definition\CompositeType;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\InterfaceType;
use GraphQL\Type\Definition\LeafType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use GraphQL\Utils\AST;
use GraphQL\Utils\Utils;
use SplQueue;
use stdClass;
use Throwable;
use function count;
use function is_array;
use function is_string;
use function sprintf;
class CoroutineExecutor implements Runtime, ExecutorImplementation
{
/** @var object */
private static $undefined;
/** @var Schema */
private $schema;
/** @var callable */
private $fieldResolver;
/** @var PromiseAdapter */
private $promiseAdapter;
/** @var mixed|null */
private $rootValue;
/** @var mixed|null */
private $contextValue;
/** @var mixed|null */
private $rawVariableValues;
/** @var mixed|null */
private $variableValues;
/** @var DocumentNode */
private $documentNode;
/** @var string|null */
private $operationName;
/** @var Collector|null */
private $collector;
/** @var array<Error> */
private $errors;
/** @var SplQueue */
private $queue;
/** @var SplQueue */
private $schedule;
/** @var stdClass|null */
private $rootResult;
/** @var int|null */
private $pending;
/** @var callable */
private $doResolve;
public function __construct(
PromiseAdapter $promiseAdapter,
Schema $schema,
DocumentNode $documentNode,
$rootValue,
$contextValue,
$rawVariableValues,
?string $operationName,
callable $fieldResolver
) {
if (self::$undefined === null) {
self::$undefined = Utils::undefined();
}
$this->errors = [];
$this->queue = new SplQueue();
$this->schedule = new SplQueue();
$this->schema = $schema;
$this->fieldResolver = $fieldResolver;
$this->promiseAdapter = $promiseAdapter;
$this->rootValue = $rootValue;
$this->contextValue = $contextValue;
$this->rawVariableValues = $rawVariableValues;
$this->documentNode = $documentNode;
$this->operationName = $operationName;
}
public static function create(
PromiseAdapter $promiseAdapter,
Schema $schema,
DocumentNode $documentNode,
$rootValue,
$contextValue,
$variableValues,
?string $operationName,
callable $fieldResolver
) {
return new static(
$promiseAdapter,
$schema,
$documentNode,
$rootValue,
$contextValue,
$variableValues,
$operationName,
$fieldResolver
);
}
private static function resultToArray($value, $emptyObjectAsStdClass = true)
{
if ($value instanceof stdClass) {
$array = (array) $value;
foreach ($array as $propertyName => $propertyValue) {
$array[$propertyName] = self::resultToArray($propertyValue);
}
if ($emptyObjectAsStdClass && count($array) === 0) {
return new stdClass();
}
return $array;
}
if (is_array($value)) {
$array = [];
foreach ($value as $key => $item) {
$array[$key] = self::resultToArray($item);
}
return $array;
}
return $value;
}
public function doExecute() : Promise
{
$this->rootResult = new stdClass();
$this->errors = [];
$this->queue = new SplQueue();
$this->schedule = new SplQueue();
$this->pending = 0;
$this->collector = new Collector($this->schema, $this);
$this->collector->initialize($this->documentNode, $this->operationName);
if (count($this->errors) > 0) {
return $this->promiseAdapter->createFulfilled($this->finishExecute(null, $this->errors));
}
[$errors, $coercedVariableValues] = Values::getVariableValues(
$this->schema,
$this->collector->operation->variableDefinitions ?? [],
$this->rawVariableValues ?? []
);
if (count($errors ?? []) > 0) {
return $this->promiseAdapter->createFulfilled($this->finishExecute(null, $errors));
}
$this->variableValues = $coercedVariableValues;
foreach ($this->collector->collectFields($this->collector->rootType, $this->collector->operation->selectionSet) as $shared) {
/** @var CoroutineContextShared $shared */
// !!! assign to keep object keys sorted
$this->rootResult->{$shared->resultName} = null;
$ctx = new CoroutineContext(
$shared,
$this->collector->rootType,
$this->rootValue,
$this->rootResult,
[$shared->resultName]
);
$fieldDefinition = $this->findFieldDefinition($ctx);
if (! $fieldDefinition->getType() instanceof NonNull) {
$ctx->nullFence = [$shared->resultName];
}
if ($this->collector->operation->operation === 'mutation' && ! $this->queue->isEmpty()) {
$this->schedule->enqueue($ctx);
} else {
$this->queue->enqueue(new Strand($this->spawn($ctx)));
}
}
$this->run();
if ($this->pending > 0) {
return $this->promiseAdapter->create(function (callable $resolve) : void {
$this->doResolve = $resolve;
});
}
return $this->promiseAdapter->createFulfilled($this->finishExecute($this->rootResult, $this->errors));
}
/**
* @param object|null $value
* @param Error[] $errors
*/
private function finishExecute($value, array $errors) : ExecutionResult
{
$this->rootResult = null;
$this->errors = [];
$this->queue = new SplQueue();
$this->schedule = new SplQueue();
$this->pending = null;
$this->collector = null;
$this->variableValues = null;
if ($value !== null) {
$value = self::resultToArray($value, false);
}
return new ExecutionResult($value, $errors);
}
/**
* @internal
*
* @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type
*/
public function evaluate(ValueNode $valueNode, InputType $type)
{
return AST::valueFromAST($valueNode, $type, $this->variableValues);
}
/**
* @internal
*/
public function addError($error)
{
$this->errors[] = $error;
}
private function run()
{
RUN:
while (! $this->queue->isEmpty()) {
/** @var Strand $strand */
$strand = $this->queue->dequeue();
try {
if ($strand->success !== null) {
RESUME:
if ($strand->success) {
$strand->current->send($strand->value);
} else {
$strand->current->throw($strand->value);
}
$strand->success = null;
$strand->value = null;
}
START:
if ($strand->current->valid()) {
$value = $strand->current->current();
if ($value instanceof Generator) {
$strand->stack[$strand->depth++] = $strand->current;
$strand->current = $value;
goto START;
} elseif ($this->isPromise($value)) {
// !!! increment pending before calling ->then() as it may invoke the callback right away
++$this->pending;
if (! $value instanceof Promise) {
$value = $this->promiseAdapter->convertThenable($value);
}
$this->promiseAdapter
->then(
$value,
function ($value) use ($strand) : void {
$strand->success = true;
$strand->value = $value;
$this->queue->enqueue($strand);
$this->done();
},
function (Throwable $throwable) use ($strand) : void {
$strand->success = false;
$strand->value = $throwable;
$this->queue->enqueue($strand);
$this->done();
}
);
continue;
} else {
$strand->success = true;
$strand->value = $value;
goto RESUME;
}
}
$strand->success = true;
$strand->value = $strand->current->getReturn();
} catch (Throwable $reason) {
$strand->success = false;
$strand->value = $reason;
}
if ($strand->depth <= 0) {
continue;
}
$current = &$strand->stack[--$strand->depth];
$strand->current = $current;
$current = null;
goto RESUME;
}
if ($this->pending > 0 || $this->schedule->isEmpty()) {
return;
}
/** @var CoroutineContext $ctx */
$ctx = $this->schedule->dequeue();
$this->queue->enqueue(new Strand($this->spawn($ctx)));
goto RUN;
}
private function done()
{
--$this->pending;
$this->run();
if ($this->pending > 0) {
return;
}
$doResolve = $this->doResolve;
$doResolve($this->finishExecute($this->rootResult, $this->errors));
}
private function spawn(CoroutineContext $ctx)
{
// short-circuit evaluation for __typename
if ($ctx->shared->fieldName === Introspection::TYPE_NAME_FIELD_NAME) {
$ctx->result->{$ctx->shared->resultName} = $ctx->type->name;
return;
}
try {
if ($ctx->shared->typeGuard1 === $ctx->type) {
$resolve = $ctx->shared->resolveIfType1;
$ctx->resolveInfo = clone $ctx->shared->resolveInfoIfType1;
$ctx->resolveInfo->path = $ctx->path;
$arguments = $ctx->shared->argumentsIfType1;
$returnType = $ctx->resolveInfo->returnType;
} else {
$fieldDefinition = $this->findFieldDefinition($ctx);
if ($fieldDefinition->resolveFn !== null) {
$resolve = $fieldDefinition->resolveFn;
} elseif ($ctx->type->resolveFieldFn !== null) {
$resolve = $ctx->type->resolveFieldFn;
} else {
$resolve = $this->fieldResolver;
}
$returnType = $fieldDefinition->getType();
$ctx->resolveInfo = new ResolveInfo(
$fieldDefinition,
$ctx->shared->fieldNodes,
$ctx->type,
$ctx->path,
$this->schema,
$this->collector->fragments,
$this->rootValue,
$this->collector->operation,
$this->variableValues
);
$arguments = Values::getArgumentValuesForMap(
$fieldDefinition,
$ctx->shared->argumentValueMap,
$this->variableValues
);
// !!! assign only in batch when no exception can be thrown in-between
$ctx->shared->typeGuard1 = $ctx->type;
$ctx->shared->resolveIfType1 = $resolve;
$ctx->shared->argumentsIfType1 = $arguments;
$ctx->shared->resolveInfoIfType1 = $ctx->resolveInfo;
}
$value = $resolve($ctx->value, $arguments, $this->contextValue, $ctx->resolveInfo);
if (! $this->completeValueFast($ctx, $returnType, $value, $ctx->path, $returnValue)) {
$returnValue = yield $this->completeValue(
$ctx,
$returnType,
$value,
$ctx->path,
$ctx->nullFence
);
}
} catch (Throwable $reason) {
$this->addError(Error::createLocatedError(
$reason,
$ctx->shared->fieldNodes,
$ctx->path
));
$returnValue = self::$undefined;
}
if ($returnValue !== self::$undefined) {
$ctx->result->{$ctx->shared->resultName} = $returnValue;
} elseif ($ctx->resolveInfo !== null && $ctx->resolveInfo->returnType instanceof NonNull) { // !!! $ctx->resolveInfo might not have been initialized yet
$result =& $this->rootResult;
foreach ($ctx->nullFence ?? [] as $key) {
if (is_string($key)) {
$result =& $result->{$key};
} else {
$result =& $result[$key];
}
}
$result = null;
}
}
private function findFieldDefinition(CoroutineContext $ctx)
{
if ($ctx->shared->fieldName === Introspection::SCHEMA_FIELD_NAME && $ctx->type === $this->schema->getQueryType()) {
return Introspection::schemaMetaFieldDef();
}
if ($ctx->shared->fieldName === Introspection::TYPE_FIELD_NAME && $ctx->type === $this->schema->getQueryType()) {
return Introspection::typeMetaFieldDef();
}
if ($ctx->shared->fieldName === Introspection::TYPE_NAME_FIELD_NAME) {
return Introspection::typeNameMetaFieldDef();
}
return $ctx->type->getField($ctx->shared->fieldName);
}
/**
* @param mixed $value
* @param string[] $path
* @param mixed $returnValue
*/
private function completeValueFast(CoroutineContext $ctx, Type $type, $value, array $path, &$returnValue) : bool
{
// special handling of Throwable inherited from JS reference implementation, but makes no sense in this PHP
if ($this->isPromise($value) || $value instanceof Throwable) {
return false;
}
$nonNull = false;
if ($type instanceof NonNull) {
$nonNull = true;
$type = $type->getWrappedType();
}
if (! $type instanceof LeafType) {
return false;
}
if ($type !== $this->schema->getType($type->name)) {
$hint = '';
if ($this->schema->getConfig()->typeLoader !== null) {
$hint = sprintf(
'Make sure that type loader returns the same instance as defined in %s.%s',
$ctx->type,
$ctx->shared->fieldName
);
}
$this->addError(Error::createLocatedError(
new InvariantViolation(
sprintf(
'Schema must contain unique named types but contains multiple types named "%s". %s ' .
'(see http://webonyx.github.io/graphql-php/type-system/#type-registry).',
$type->name,
$hint
)
),
$ctx->shared->fieldNodes,
$path
));
$value = null;
}
if ($value === null) {
$returnValue = null;
} else {
try {
$returnValue = $type->serialize($value);
} catch (Throwable $error) {
$this->addError(Error::createLocatedError(
new InvariantViolation(
'Expected a value of type "' . Utils::printSafe($type) . '" but received: ' . Utils::printSafe($value),
0,
$error
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
}
}
if ($nonNull && $returnValue === null) {
$this->addError(Error::createLocatedError(
new InvariantViolation(sprintf(
'Cannot return null for non-nullable field "%s.%s".',
$ctx->type->name,
$ctx->shared->fieldName
)),
$ctx->shared->fieldNodes,
$path
));
$returnValue = self::$undefined;
}
return true;
}
/**
* @param mixed $value
* @param string[] $path
* @param string[]|null $nullFence
*
* @return mixed
*/
private function completeValue(CoroutineContext $ctx, Type $type, $value, array $path, ?array $nullFence)
{
$nonNull = false;
$returnValue = null;
if ($type instanceof NonNull) {
$nonNull = true;
$type = $type->getWrappedType();
} else {
$nullFence = $path;
}
// !!! $value might be promise, yield to resolve
try {
if ($this->isPromise($value)) {
$value = yield $value;
}
} catch (Throwable $reason) {
$this->addError(Error::createLocatedError(
$reason,
$ctx->shared->fieldNodes,
$path
));
if ($nonNull) {
$returnValue = self::$undefined;
} else {
$returnValue = null;
}
goto CHECKED_RETURN;
}
if ($value === null) {
$returnValue = $value;
goto CHECKED_RETURN;
} elseif ($value instanceof Throwable) {
// special handling of Throwable inherited from JS reference implementation, but makes no sense in this PHP
$this->addError(Error::createLocatedError(
$value,
$ctx->shared->fieldNodes,
$path
));
if ($nonNull) {
$returnValue = self::$undefined;
} else {
$returnValue = null;
}
goto CHECKED_RETURN;
}
if ($type instanceof ListOfType) {
$returnValue = [];
$index = -1;
$itemType = $type->getWrappedType();
foreach ($value as $itemValue) {
++$index;
$itemPath = $path;
$itemPath[] = $index; // !!! use arrays COW semantics
$ctx->resolveInfo->path = $itemPath;
try {
if (! $this->completeValueFast($ctx, $itemType, $itemValue, $itemPath, $itemReturnValue)) {
$itemReturnValue = yield $this->completeValue($ctx, $itemType, $itemValue, $itemPath, $nullFence);
}
} catch (Throwable $reason) {
$this->addError(Error::createLocatedError(
$reason,
$ctx->shared->fieldNodes,
$itemPath
));
$itemReturnValue = null;
}
if ($itemReturnValue === self::$undefined) {
$returnValue = self::$undefined;
goto CHECKED_RETURN;
}
$returnValue[$index] = $itemReturnValue;
}
goto CHECKED_RETURN;
} else {
if ($type !== $this->schema->getType($type->name)) {
$hint = '';
if ($this->schema->getConfig()->typeLoader !== null) {
$hint = sprintf(
'Make sure that type loader returns the same instance as defined in %s.%s',
$ctx->type,
$ctx->shared->fieldName
);
}
$this->addError(Error::createLocatedError(
new InvariantViolation(
sprintf(
'Schema must contain unique named types but contains multiple types named "%s". %s ' .
'(see http://webonyx.github.io/graphql-php/type-system/#type-registry).',
$type->name,
$hint
)
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
}
if ($type instanceof LeafType) {
try {
$returnValue = $type->serialize($value);
} catch (Throwable $error) {
$this->addError(Error::createLocatedError(
new InvariantViolation(
'Expected a value of type "' . Utils::printSafe($type) . '" but received: ' . Utils::printSafe($value),
0,
$error
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
}
goto CHECKED_RETURN;
} elseif ($type instanceof CompositeType) {
/** @var ObjectType|null $objectType */
$objectType = null;
if ($type instanceof InterfaceType || $type instanceof UnionType) {
$objectType = $type->resolveType($value, $this->contextValue, $ctx->resolveInfo);
if ($objectType === null) {
$objectType = yield $this->resolveTypeSlow($ctx, $value, $type);
}
// !!! $objectType->resolveType() might return promise, yield to resolve
$objectType = yield $objectType;
if (is_string($objectType)) {
$objectType = $this->schema->getType($objectType);
}
if ($objectType === null) {
$this->addError(Error::createLocatedError(
sprintf(
'Composite type "%s" did not resolve concrete object type for value: %s.',
$type->name,
Utils::printSafe($value)
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = self::$undefined;
goto CHECKED_RETURN;
} elseif (! $objectType instanceof ObjectType) {
$this->addError(Error::createLocatedError(
new InvariantViolation(sprintf(
'Abstract type %s must resolve to an Object type at ' .
'runtime for field %s.%s with value "%s", received "%s". ' .
'Either the %s type should provide a "resolveType" ' .
'function or each possible type should provide an "isTypeOf" function.',
$type,
$ctx->resolveInfo->parentType,
$ctx->resolveInfo->fieldName,
Utils::printSafe($value),
Utils::printSafe($objectType),
$type
)),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
} elseif (! $this->schema->isSubType($type, $objectType)) {
$this->addError(Error::createLocatedError(
new InvariantViolation(sprintf(
'Runtime Object type "%s" is not a possible type for "%s".',
$objectType,
$type
)),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
} elseif ($objectType !== $this->schema->getType($objectType->name)) {
$this->addError(Error::createLocatedError(
new InvariantViolation(
sprintf(
'Schema must contain unique named types but contains multiple types named "%s". ' .
'Make sure that `resolveType` function of abstract type "%s" returns the same ' .
'type instance as referenced anywhere else within the schema ' .
'(see http://webonyx.github.io/graphql-php/type-system/#type-registry).',
$objectType,
$type
)
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
}
} elseif ($type instanceof ObjectType) {
$objectType = $type;
} else {
$this->addError(Error::createLocatedError(
sprintf(
'Unexpected field type "%s".',
Utils::printSafe($type)
),
$ctx->shared->fieldNodes,
$path
));
$returnValue = self::$undefined;
goto CHECKED_RETURN;
}
$typeCheck = $objectType->isTypeOf($value, $this->contextValue, $ctx->resolveInfo);
if ($typeCheck !== null) {
// !!! $objectType->isTypeOf() might return promise, yield to resolve
$typeCheck = yield $typeCheck;
if (! $typeCheck) {
$this->addError(Error::createLocatedError(
sprintf('Expected value of type "%s" but got: %s.', $type->name, Utils::printSafe($value)),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
}
}
$returnValue = new stdClass();
if ($ctx->shared->typeGuard2 === $objectType) {
foreach ($ctx->shared->childContextsIfType2 as $childCtx) {
$childCtx = clone $childCtx;
$childCtx->type = $objectType;
$childCtx->value = $value;
$childCtx->result = $returnValue;
$childCtx->path = $path;
$childCtx->path[] = $childCtx->shared->resultName; // !!! uses array COW semantics
$childCtx->nullFence = $nullFence;
$childCtx->resolveInfo = null;
$this->queue->enqueue(new Strand($this->spawn($childCtx)));
// !!! assign null to keep object keys sorted
$returnValue->{$childCtx->shared->resultName} = null;
}
} else {
$childContexts = [];
$fields = [];
if ($this->collector !== null) {
$fields = $this->collector->collectFields(
$objectType,
$ctx->shared->mergedSelectionSet ?? $this->mergeSelectionSets($ctx)
);
}
/** @var CoroutineContextShared $childShared */
foreach ($fields as $childShared) {
$childPath = $path;
$childPath[] = $childShared->resultName; // !!! uses array COW semantics
$childCtx = new CoroutineContext(
$childShared,
$objectType,
$value,
$returnValue,
$childPath,
$nullFence
);
$childContexts[] = $childCtx;
$this->queue->enqueue(new Strand($this->spawn($childCtx)));
// !!! assign null to keep object keys sorted
$returnValue->{$childShared->resultName} = null;
}
$ctx->shared->typeGuard2 = $objectType;
$ctx->shared->childContextsIfType2 = $childContexts;
}
goto CHECKED_RETURN;
} else {
$this->addError(Error::createLocatedError(
sprintf('Unhandled type "%s".', Utils::printSafe($type)),
$ctx->shared->fieldNodes,
$path
));
$returnValue = null;
goto CHECKED_RETURN;
}
}
CHECKED_RETURN:
if ($nonNull && $returnValue === null) {
$this->addError(Error::createLocatedError(
new InvariantViolation(sprintf(
'Cannot return null for non-nullable field "%s.%s".',
$ctx->type->name,
$ctx->shared->fieldName
)),
$ctx->shared->fieldNodes,
$path
));
return self::$undefined;
}
return $returnValue;
}
private function mergeSelectionSets(CoroutineContext $ctx)
{
$selections = [];
foreach ($ctx->shared->fieldNodes as $fieldNode) {
if ($fieldNode->selectionSet === null) {
continue;
}
foreach ($fieldNode->selectionSet->selections as $selection) {
$selections[] = $selection;
}
}
return $ctx->shared->mergedSelectionSet = new SelectionSetNode(['selections' => $selections]);
}
/**
* @param InterfaceType|UnionType $abstractType
*
* @return Generator|ObjectType|Type|null
*/
private function resolveTypeSlow(CoroutineContext $ctx, $value, AbstractType $abstractType)
{
if ($value !== null &&
is_array($value) &&
isset($value['__typename']) &&
is_string($value['__typename'])
) {
return $this->schema->getType($value['__typename']);
}
if ($abstractType instanceof InterfaceType && $this->schema->getConfig()->typeLoader !== null) {
Warning::warnOnce(
sprintf(
'GraphQL Interface Type `%s` returned `null` from its `resolveType` function ' .
'for value: %s. Switching to slow resolution method using `isTypeOf` ' .
'of all possible implementations. It requires full schema scan and degrades query performance significantly. ' .
' Make sure your `resolveType` always returns valid implementation or throws.',
$abstractType->name,
Utils::printSafe($value)
),
Warning::WARNING_FULL_SCHEMA_SCAN
);
}
$possibleTypes = $this->schema->getPossibleTypes($abstractType);
// to be backward-compatible with old executor, ->isTypeOf() is called for all possible types,
// it cannot short-circuit when the match is found
$selectedType = null;
foreach ($possibleTypes as $type) {
$typeCheck = yield $type->isTypeOf($value, $this->contextValue, $ctx->resolveInfo);
if ($selectedType !== null || ! $typeCheck) {
continue;
}
$selectedType = $type;
}
return $selectedType;
}
/**
* @param mixed $value
*
* @return bool
*/
private function isPromise($value)
{
return $value instanceof Promise || $this->promiseAdapter->isThenable($value);
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use GraphQL\Language\AST\ValueNode;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ScalarType;
/**
* @internal
*/
interface Runtime
{
/**
* @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type
*/
public function evaluate(ValueNode $valueNode, InputType $type);
public function addError($error);
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace GraphQL\Experimental\Executor;
use Generator;
/**
* @internal
*/
class Strand
{
/** @var Generator */
public $current;
/** @var Generator[] */
public $stack;
/** @var int */
public $depth;
/** @var bool|null */
public $success;
/** @var mixed */
public $value;
public function __construct(Generator $coroutine)
{
$this->current = $coroutine;
$this->stack = [];
$this->depth = 0;
}
}
+163 -98
View File
@@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
namespace GraphQL;
use GraphQL\Error\Error;
@@ -6,15 +9,23 @@ use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\Executor;
use GraphQL\Executor\Promise\Adapter\SyncPromiseAdapter;
use GraphQL\Executor\Promise\Promise;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Executor\ReferenceExecutor;
use GraphQL\Experimental\Executor\CoroutineExecutor;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\Parser;
use GraphQL\Language\Source;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema as SchemaType;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Validator\Rules\AbstractValidationRule;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\ValidationRule;
use function array_values;
use function count;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* This is the primary facade for fulfilling GraphQL operations.
@@ -38,9 +49,11 @@ class GraphQL
* rootValue:
* The value provided as the first argument to resolver functions on the top
* level type (e.g. the query object type).
* context:
* The value provided as the third argument to all resolvers.
* Use this to pass current session, user data, etc
* contextValue:
* The context value is provided as an argument to resolver functions after
* field arguments. It is used to pass shared information useful at any point
* during executing this query, for example the currently logged in user and
* connections to databases or other services.
* variableValues:
* A mapping of variable name to runtime value to use for all variables
* defined in the requestString.
@@ -57,33 +70,37 @@ class GraphQL
* Empty array would allow to skip query validation (may be convenient for persisted
* queries which are validated before persisting and assumed valid during execution)
*
* @api
* @param \GraphQL\Type\Schema $schema
* @param string|DocumentNode $source
* @param mixed $rootValue
* @param mixed $context
* @param array|null $variableValues
* @param string|null $operationName
* @param callable $fieldResolver
* @param array $validationRules
* @param mixed $rootValue
* @param mixed $contextValue
* @param mixed[]|null $variableValues
* @param ValidationRule[] $validationRules
*
* @return ExecutionResult
* @api
*/
public static function executeQuery(
\GraphQL\Type\Schema $schema,
SchemaType $schema,
$source,
$rootValue = null,
$context = null,
$contextValue = null,
$variableValues = null,
$operationName = null,
callable $fieldResolver = null,
array $validationRules = null
)
{
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
) : ExecutionResult {
$promiseAdapter = new SyncPromiseAdapter();
$promise = self::promiseToExecute($promiseAdapter, $schema, $source, $rootValue, $context,
$variableValues, $operationName, $fieldResolver, $validationRules);
$promise = self::promiseToExecute(
$promiseAdapter,
$schema,
$source,
$rootValue,
$contextValue,
$variableValues,
$operationName,
$fieldResolver,
$validationRules
);
return $promiseAdapter->wait($promise);
}
@@ -92,69 +109,65 @@ class GraphQL
* Same as executeQuery(), but requires PromiseAdapter and always returns a Promise.
* Useful for Async PHP platforms.
*
* @api
* @param PromiseAdapter $promiseAdapter
* @param \GraphQL\Type\Schema $schema
* @param string|DocumentNode $source
* @param mixed $rootValue
* @param mixed $context
* @param array|null $variableValues
* @param string|null $operationName
* @param callable $fieldResolver
* @param array $validationRules
* @param string|DocumentNode $source
* @param mixed $rootValue
* @param mixed $context
* @param mixed[]|null $variableValues
* @param ValidationRule[]|null $validationRules
*
* @return Promise
* @api
*/
public static function promiseToExecute(
PromiseAdapter $promiseAdapter,
\GraphQL\Type\Schema $schema,
SchemaType $schema,
$source,
$rootValue = null,
$context = null,
$variableValues = null,
$operationName = null,
callable $fieldResolver = null,
array $validationRules = null
)
{
?string $operationName = null,
?callable $fieldResolver = null,
?array $validationRules = null
) : Promise {
try {
if ($source instanceof DocumentNode) {
$documentNode = $source;
} else {
$documentNode = Parser::parse(new Source($source ?: '', 'GraphQL'));
$documentNode = Parser::parse(new Source($source ?? '', 'GraphQL'));
}
// FIXME
if (!empty($validationRules)) {
foreach ($validationRules as $rule) {
if ($rule instanceof QueryComplexity) {
$rule->setRawVariableValues($variableValues);
}
}
} else {
if (count($validationRules ?? []) === 0) {
/** @var QueryComplexity $queryComplexity */
$queryComplexity = DocumentValidator::getRule(QueryComplexity::class);
$queryComplexity->setRawVariableValues($variableValues);
} else {
foreach ($validationRules as $rule) {
if (! ($rule instanceof QueryComplexity)) {
continue;
}
$rule->setRawVariableValues($variableValues);
}
}
$validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules);
if (!empty($validationErrors)) {
if (count($validationErrors) > 0) {
return $promiseAdapter->createFulfilled(
new ExecutionResult(null, $validationErrors)
);
} else {
return Executor::promiseToExecute(
$promiseAdapter,
$schema,
$documentNode,
$rootValue,
$context,
$variableValues,
$operationName,
$fieldResolver
);
}
return Executor::promiseToExecute(
$promiseAdapter,
$schema,
$documentNode,
$rootValue,
$context,
$variableValues,
$operationName,
$fieldResolver
);
} catch (Error $e) {
return $promiseAdapter->createFulfilled(
new ExecutionResult(null, [$e])
@@ -165,25 +178,31 @@ class GraphQL
/**
* @deprecated Use executeQuery()->toArray() instead
*
* @param \GraphQL\Type\Schema $schema
* @param string|DocumentNode $source
* @param mixed $rootValue
* @param mixed $contextValue
* @param array|null $variableValues
* @param string|null $operationName
* @return Promise|array
* @param mixed $rootValue
* @param mixed $contextValue
* @param mixed[]|null $variableValues
*
* @return Promise|mixed[]
*
* @codeCoverageIgnore
*/
public static function execute(
\GraphQL\Type\Schema $schema,
SchemaType $schema,
$source,
$rootValue = null,
$contextValue = null,
$variableValues = null,
$operationName = null
)
{
$result = self::promiseToExecute(
$promiseAdapter = Executor::getPromiseAdapter(),
?string $operationName = null
) {
trigger_error(
__METHOD__ . ' is deprecated, use GraphQL::executeQuery()->toArray() as a quick replacement',
E_USER_DEPRECATED
);
$promiseAdapter = Executor::getPromiseAdapter();
$result = self::promiseToExecute(
$promiseAdapter,
$schema,
$source,
$rootValue,
@@ -195,36 +214,42 @@ class GraphQL
if ($promiseAdapter instanceof SyncPromiseAdapter) {
$result = $promiseAdapter->wait($result)->toArray();
} else {
$result = $result->then(function(ExecutionResult $r) {
$result = $result->then(static function (ExecutionResult $r) : array {
return $r->toArray();
});
}
return $result;
}
/**
* @deprecated renamed to executeQuery()
*
* @param \GraphQL\Type\Schema $schema
* @param string|DocumentNode $source
* @param mixed $rootValue
* @param mixed $contextValue
* @param array|null $variableValues
* @param string|null $operationName
* @param mixed $rootValue
* @param mixed $contextValue
* @param mixed[]|null $variableValues
*
* @return ExecutionResult|Promise
*
* @codeCoverageIgnore
*/
public static function executeAndReturnResult(
\GraphQL\Type\Schema $schema,
SchemaType $schema,
$source,
$rootValue = null,
$contextValue = null,
$variableValues = null,
$operationName = null
)
{
$result = self::promiseToExecute(
$promiseAdapter = Executor::getPromiseAdapter(),
?string $operationName = null
) {
trigger_error(
__METHOD__ . ' is deprecated, use GraphQL::executeQuery() as a quick replacement',
E_USER_DEPRECATED
);
$promiseAdapter = Executor::getPromiseAdapter();
$result = self::promiseToExecute(
$promiseAdapter,
$schema,
$source,
$rootValue,
@@ -232,19 +257,22 @@ class GraphQL
$variableValues,
$operationName
);
if ($promiseAdapter instanceof SyncPromiseAdapter) {
$result = $promiseAdapter->wait($result);
}
return $result;
}
/**
* Returns directives defined in GraphQL spec
*
* @api
* @return Directive[]
*
* @api
*/
public static function getStandardDirectives()
public static function getStandardDirectives() : array
{
return array_values(Directive::getInternalDirectives());
}
@@ -252,48 +280,85 @@ class GraphQL
/**
* Returns types defined in GraphQL spec
*
* @api
* @return Type[]
*
* @api
*/
public static function getStandardTypes()
public static function getStandardTypes() : array
{
return array_values(Type::getInternalTypes());
return array_values(Type::getStandardTypes());
}
/**
* Replaces standard types with types from this list (matching by name)
* Standard types not listed here remain untouched.
*
* @param array<string, ScalarType> $types
*
* @api
*/
public static function overrideStandardTypes(array $types)
{
Type::overrideStandardTypes($types);
}
/**
* Returns standard validation rules implementing GraphQL spec
*
* @return ValidationRule[]
*
* @api
* @return AbstractValidationRule[]
*/
public static function getStandardValidationRules()
public static function getStandardValidationRules() : array
{
return array_values(DocumentValidator::defaultRules());
}
/**
* @param callable $fn
* Set default resolver implementation
*
* @api
*/
public static function setDefaultFieldResolver(callable $fn)
public static function setDefaultFieldResolver(callable $fn) : void
{
Executor::setDefaultFieldResolver($fn);
}
/**
* @param PromiseAdapter|null $promiseAdapter
*/
public static function setPromiseAdapter(PromiseAdapter $promiseAdapter = null)
public static function setPromiseAdapter(?PromiseAdapter $promiseAdapter = null) : void
{
Executor::setPromiseAdapter($promiseAdapter);
}
/**
* Experimental: Switch to the new executor
*/
public static function useExperimentalExecutor()
{
trigger_error(
'Experimental Executor is deprecated and will be removed in the next major version',
E_USER_DEPRECATED
);
Executor::setImplementationFactory([CoroutineExecutor::class, 'create']);
}
/**
* Experimental: Switch back to the default executor
*/
public static function useReferenceExecutor()
{
Executor::setImplementationFactory([ReferenceExecutor::class, 'create']);
}
/**
* Returns directives defined in GraphQL spec
*
* @deprecated Renamed to getStandardDirectives
*
* @return Directive[]
*
* @codeCoverageIgnore
*/
public static function getInternalDirectives()
public static function getInternalDirectives() : array
{
return self::getStandardDirectives();
}
+6 -6
View File
@@ -1,17 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ArgumentNode extends Node
{
/** @var string */
public $kind = NodeKind::ARGUMENT;
/**
* @var ValueNode
*/
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode */
public $value;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
}
@@ -1,13 +1,14 @@
<?php
namespace GraphQL\Language\AST;
declare(strict_types=1);
namespace GraphQL\Language\AST;
class BooleanValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::BOOLEAN;
/**
* @var string
*/
/** @var bool */
public $value;
}
@@ -1,11 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type DefinitionNode =
* | ExecutableDefinitionNode
* | TypeSystemDefinitionNode;
*/
interface DefinitionNode
{
/**
* export type DefinitionNode = OperationDefinitionNode
* | FragmentDefinitionNode
* | TypeSystemDefinitionNode // experimental non-spec addition.
*/
}
@@ -1,25 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class DirectiveDefinitionNode extends Node implements TypeSystemDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::DIRECTIVE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var ArgumentNode[]
*/
/** @var StringValueNode|null */
public $description;
/** @var NodeList<InputValueDefinitionNode> */
public $arguments;
/**
* @var NameNode[]
*/
/** @var bool */
public $repeatable;
/** @var NodeList<NameNode> */
public $locations;
}
@@ -1,17 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class DirectiveNode extends Node
{
/** @var string */
public $kind = NodeKind::DIRECTIVE;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var ArgumentNode[]
*/
/** @var NodeList<ArgumentNode> */
public $arguments;
}
+5 -3
View File
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class DocumentNode extends Node
{
/** @var string */
public $kind = NodeKind::DOCUMENT;
/**
* @var DefinitionNode[]
*/
/** @var NodeList<DefinitionNode&Node> */
public $definitions;
}
@@ -1,30 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class EnumTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::ENUM_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var EnumValueDefinitionNode[]
*/
/** @var NodeList<EnumValueDefinitionNode> */
public $values;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class EnumTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::ENUM_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<EnumValueDefinitionNode> */
public $values;
}
@@ -1,25 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class EnumValueDefinitionNode extends Node
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::ENUM_VALUE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class EnumValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::ENUM;
/**
* @var string
*/
/** @var string */
public $value;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type ExecutableDefinitionNode =
* | OperationDefinitionNode
* | FragmentDefinitionNode;
*/
interface ExecutableDefinitionNode extends DefinitionNode
{
}
@@ -1,35 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class FieldDefinitionNode extends Node
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::FIELD_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var InputValueDefinitionNode[]
*/
/** @var NodeList<InputValueDefinitionNode> */
public $arguments;
/**
* @var TypeNode
*/
/** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */
public $type;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
+9 -15
View File
@@ -1,32 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class FieldNode extends Node implements SelectionNode
{
/** @var string */
public $kind = NodeKind::FIELD;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var NameNode|null
*/
/** @var NameNode|null */
public $alias;
/**
* @var ArgumentNode[]|null
*/
/** @var NodeList<ArgumentNode> */
public $arguments;
/**
* @var DirectiveNode[]|null
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var SelectionSetNode|null
*/
/** @var SelectionSetNode|null */
public $selectionSet;
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class FloatValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::FLOAT;
/**
* @var string
*/
/** @var string */
public $value;
}
@@ -1,27 +1,31 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class FragmentDefinitionNode extends Node implements DefinitionNode, HasSelectionSet
class FragmentDefinitionNode extends Node implements ExecutableDefinitionNode, HasSelectionSet
{
/** @var string */
public $kind = NodeKind::FRAGMENT_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var NamedTypeNode
* Note: fragment variable definitions are experimental and may be changed
* or removed in the future.
*
* @var NodeList<VariableDefinitionNode>
*/
public $variableDefinitions;
/** @var NamedTypeNode */
public $typeCondition;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var SelectionSetNode
*/
/** @var SelectionSetNode */
public $selectionSet;
}
@@ -1,17 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class FragmentSpreadNode extends Node implements SelectionNode
{
/** @var string */
public $kind = NodeKind::FRAGMENT_SPREAD;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
}
@@ -1,10 +1,15 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type DefinitionNode = OperationDefinitionNode
* | FragmentDefinitionNode
*
* @property SelectionSetNode $selectionSet
*/
interface HasSelectionSet
{
/**
* export type DefinitionNode = OperationDefinitionNode
* | FragmentDefinitionNode
*/
}
@@ -1,22 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InlineFragmentNode extends Node implements SelectionNode
{
/** @var string */
public $kind = NodeKind::INLINE_FRAGMENT;
/**
* @var NamedTypeNode
*/
/** @var NamedTypeNode */
public $typeCondition;
/**
* @var DirectiveNode[]|null
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var SelectionSetNode
*/
/** @var SelectionSetNode */
public $selectionSet;
}
@@ -1,30 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InputObjectTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::INPUT_OBJECT_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var InputValueDefinitionNode[]
*/
/** @var NodeList<InputValueDefinitionNode> */
public $fields;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InputObjectTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::INPUT_OBJECT_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<InputValueDefinitionNode> */
public $fields;
}
@@ -1,35 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InputValueDefinitionNode extends Node
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::INPUT_VALUE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var TypeNode
*/
/** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */
public $type;
/**
* @var ValueNode
*/
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null */
public $defaultValue;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
+5 -3
View File
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class IntValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::INT;
/**
* @var string
*/
/** @var string */
public $value;
}
@@ -1,30 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InterfaceTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::INTERFACE_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var FieldDefinitionNode[]
*/
public $fields = [];
/** @var NodeList<NamedTypeNode> */
public $interfaces;
/**
* @var string
*/
/** @var NodeList<FieldDefinitionNode> */
public $fields;
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class InterfaceTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::INTERFACE_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<InterfaceTypeDefinitionNode> */
public $interfaces;
/** @var NodeList<FieldDefinitionNode> */
public $fields;
}
+5 -3
View File
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ListTypeNode extends Node implements TypeNode
{
/** @var string */
public $kind = NodeKind::LIST_TYPE;
/**
* @var Node
*/
/** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */
public $type;
}
@@ -1,13 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ListValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::LST;
/**
* @var ValueNode[]
*/
/** @var NodeList<ValueNode&Node> */
public $values;
}
+19 -12
View File
@@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
use GraphQL\Language\Source;
@@ -27,14 +30,14 @@ class Location
/**
* The Token at which this Node begins.
*
* @var Token
* @var Token|null
*/
public $startToken;
/**
* The Token at which this Node ends.
*
* @var Token
* @var Token|null
*/
public $endToken;
@@ -46,27 +49,31 @@ class Location
public $source;
/**
* @param $start
* @param $end
* @param int $start
* @param int $end
*
* @return static
*/
public static function create($start, $end)
{
$tmp = new static();
$tmp = new static();
$tmp->start = $start;
$tmp->end = $end;
$tmp->end = $end;
return $tmp;
}
public function __construct(Token $startToken = null, Token $endToken = null, Source $source = null)
public function __construct(?Token $startToken = null, ?Token $endToken = null, ?Source $source = null)
{
$this->startToken = $startToken;
$this->endToken = $endToken;
$this->source = $source;
$this->endToken = $endToken;
$this->source = $source;
if ($startToken && $endToken) {
$this->start = $startToken->start;
$this->end = $endToken->end;
if ($startToken === null || $endToken === null) {
return;
}
$this->start = $startToken->start;
$this->end = $endToken->end;
}
}
+5 -3
View File
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class NameNode extends Node implements TypeNode
{
/** @var string */
public $kind = NodeKind::NAME;
/**
* @var string
*/
/** @var string */
public $value;
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class NamedTypeNode extends Node implements TypeNode
{
/** @var string */
public $kind = NodeKind::NAMED_TYPE;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
}
+74 -59
View File
@@ -1,55 +1,62 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
use GraphQL\Error\InvariantViolation;
use GraphQL\Utils\Utils;
use function count;
use function get_object_vars;
use function is_array;
use function is_scalar;
use function json_encode;
/**
* type Node = NameNode
* | DocumentNode
* | OperationDefinitionNode
* | VariableDefinitionNode
* | VariableNode
* | SelectionSetNode
* | FieldNode
* | ArgumentNode
* | FragmentSpreadNode
* | InlineFragmentNode
* | FragmentDefinitionNode
* | IntValueNode
* | FloatValueNode
* | StringValueNode
* | BooleanValueNode
* | EnumValueNode
* | ListValueNode
* | ObjectValueNode
* | ObjectFieldNode
* | DirectiveNode
* | ListTypeNode
* | NonNullTypeNode
*/
abstract class Node
{
/**
type Node = NameNode
| DocumentNode
| OperationDefinitionNode
| VariableDefinitionNode
| VariableNode
| SelectionSetNode
| FieldNode
| ArgumentNode
| FragmentSpreadNode
| InlineFragmentNode
| FragmentDefinitionNode
| IntValueNode
| FloatValueNode
| StringValueNode
| BooleanValueNode
| EnumValueNode
| ListValueNode
| ObjectValueNode
| ObjectFieldNode
| DirectiveNode
| ListTypeNode
| NonNullTypeNode
*/
/** @var Location|null */
public $loc;
/** @var string */
public $kind;
/**
* @var Location
*/
public $loc;
/**
* @param array $vars
* @param (NameNode|NodeList|SelectionSetNode|Location|string|int|bool|float|null)[] $vars
*/
public function __construct(array $vars)
{
if (!empty($vars)) {
Utils::assign($this, $vars);
if (count($vars) === 0) {
return;
}
Utils::assign($this, $vars);
}
/**
* @return $this
* @return self
*/
public function cloneDeep()
{
@@ -57,8 +64,9 @@ abstract class Node
}
/**
* @param $value
* @return array|Node
* @param string|NodeList|Location|Node|(Node|NodeList|Location)[] $value
*
* @return string|NodeList|Location|Node
*/
private function cloneValue($value)
{
@@ -67,7 +75,7 @@ abstract class Node
foreach ($value as $key => $arrValue) {
$cloned[$key] = $this->cloneValue($arrValue);
}
} else if ($value instanceof Node) {
} elseif ($value instanceof self) {
$cloned = clone $value;
foreach (get_object_vars($cloned) as $prop => $propValue) {
$cloned->{$prop} = $this->cloneValue($propValue);
@@ -79,61 +87,67 @@ abstract class Node
return $cloned;
}
/**
* @return string
*/
public function __toString()
public function __toString() : string
{
$tmp = $this->toArray(true);
return json_encode($tmp);
return (string) json_encode($tmp);
}
/**
* @param bool $recursive
* @return array
* @return mixed[]
*/
public function toArray($recursive = false)
public function toArray(bool $recursive = false) : array
{
if ($recursive) {
return $this->recursiveToArray($this);
} else {
$tmp = (array) $this;
}
$tmp = (array) $this;
if ($this->loc !== null) {
$tmp['loc'] = [
'start' => $this->loc->start,
'end' => $this->loc->end
'end' => $this->loc->end,
];
return $tmp;
}
return $tmp;
}
/**
* @param Node $node
* @return array
* @return mixed[]
*/
private function recursiveToArray(Node $node)
{
$result = [
'kind' => $node->kind,
'loc' => [
'start' => $node->loc->start,
'end' => $node->loc->end
]
];
if ($node->loc !== null) {
$result['loc'] = [
'start' => $node->loc->start,
'end' => $node->loc->end,
];
}
foreach (get_object_vars($node) as $prop => $propValue) {
if (isset($result[$prop]))
if (isset($result[$prop])) {
continue;
}
if ($propValue === null) {
continue;
}
if (is_array($propValue) || $propValue instanceof NodeList) {
$tmp = [];
foreach ($propValue as $tmp1) {
$tmp[] = $tmp1 instanceof Node ? $this->recursiveToArray($tmp1) : (array) $tmp1;
}
} else if ($propValue instanceof Node) {
} elseif ($propValue instanceof Node) {
$tmp = $this->recursiveToArray($propValue);
} else if (is_scalar($propValue) || null === $propValue) {
} elseif (is_scalar($propValue) || $propValue === null) {
$tmp = $propValue;
} else {
$tmp = null;
@@ -141,6 +155,7 @@ abstract class Node
$result[$prop] = $tmp;
}
return $result;
}
}
+81 -78
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class NodeKind
@@ -7,129 +9,130 @@ class NodeKind
// constants from language/kinds.js:
const NAME = 'Name';
// Document
const DOCUMENT = 'Document';
const DOCUMENT = 'Document';
const OPERATION_DEFINITION = 'OperationDefinition';
const VARIABLE_DEFINITION = 'VariableDefinition';
const VARIABLE = 'Variable';
const SELECTION_SET = 'SelectionSet';
const FIELD = 'Field';
const ARGUMENT = 'Argument';
const VARIABLE_DEFINITION = 'VariableDefinition';
const VARIABLE = 'Variable';
const SELECTION_SET = 'SelectionSet';
const FIELD = 'Field';
const ARGUMENT = 'Argument';
// Fragments
const FRAGMENT_SPREAD = 'FragmentSpread';
const INLINE_FRAGMENT = 'InlineFragment';
const FRAGMENT_SPREAD = 'FragmentSpread';
const INLINE_FRAGMENT = 'InlineFragment';
const FRAGMENT_DEFINITION = 'FragmentDefinition';
// Values
const INT = 'IntValue';
const FLOAT = 'FloatValue';
const STRING = 'StringValue';
const BOOLEAN = 'BooleanValue';
const ENUM = 'EnumValue';
const NULL = 'NullValue';
const LST = 'ListValue';
const OBJECT = 'ObjectValue';
const INT = 'IntValue';
const FLOAT = 'FloatValue';
const STRING = 'StringValue';
const BOOLEAN = 'BooleanValue';
const ENUM = 'EnumValue';
const NULL = 'NullValue';
const LST = 'ListValue';
const OBJECT = 'ObjectValue';
const OBJECT_FIELD = 'ObjectField';
// Directives
const DIRECTIVE = 'Directive';
// Types
const NAMED_TYPE = 'NamedType';
const LIST_TYPE = 'ListType';
const NAMED_TYPE = 'NamedType';
const LIST_TYPE = 'ListType';
const NON_NULL_TYPE = 'NonNullType';
// Type System Definitions
const SCHEMA_DEFINITION = 'SchemaDefinition';
const SCHEMA_DEFINITION = 'SchemaDefinition';
const OPERATION_TYPE_DEFINITION = 'OperationTypeDefinition';
// Type Definitions
const SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition';
const OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition';
const FIELD_DEFINITION = 'FieldDefinition';
const INPUT_VALUE_DEFINITION = 'InputValueDefinition';
const INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition';
const UNION_TYPE_DEFINITION = 'UnionTypeDefinition';
const ENUM_TYPE_DEFINITION = 'EnumTypeDefinition';
const ENUM_VALUE_DEFINITION = 'EnumValueDefinition';
const SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition';
const OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition';
const FIELD_DEFINITION = 'FieldDefinition';
const INPUT_VALUE_DEFINITION = 'InputValueDefinition';
const INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition';
const UNION_TYPE_DEFINITION = 'UnionTypeDefinition';
const ENUM_TYPE_DEFINITION = 'EnumTypeDefinition';
const ENUM_VALUE_DEFINITION = 'EnumValueDefinition';
const INPUT_OBJECT_TYPE_DEFINITION = 'InputObjectTypeDefinition';
// Type Extensions
const TYPE_EXTENSION_DEFINITION = 'TypeExtensionDefinition';
const SCALAR_TYPE_EXTENSION = 'ScalarTypeExtension';
const OBJECT_TYPE_EXTENSION = 'ObjectTypeExtension';
const INTERFACE_TYPE_EXTENSION = 'InterfaceTypeExtension';
const UNION_TYPE_EXTENSION = 'UnionTypeExtension';
const ENUM_TYPE_EXTENSION = 'EnumTypeExtension';
const INPUT_OBJECT_TYPE_EXTENSION = 'InputObjectTypeExtension';
// Directive Definitions
const DIRECTIVE_DEFINITION = 'DirectiveDefinition';
/**
* @todo conver to const array when moving to PHP5.6
* @var array
*/
// Type System Extensions
const SCHEMA_EXTENSION = 'SchemaExtension';
/** @var string[] */
public static $classMap = [
NodeKind::NAME => NameNode::class,
self::NAME => NameNode::class,
// Document
NodeKind::DOCUMENT => DocumentNode::class,
NodeKind::OPERATION_DEFINITION => OperationDefinitionNode::class,
NodeKind::VARIABLE_DEFINITION => VariableDefinitionNode::class,
NodeKind::VARIABLE => VariableNode::class,
NodeKind::SELECTION_SET => SelectionSetNode::class,
NodeKind::FIELD => FieldNode::class,
NodeKind::ARGUMENT => ArgumentNode::class,
self::DOCUMENT => DocumentNode::class,
self::OPERATION_DEFINITION => OperationDefinitionNode::class,
self::VARIABLE_DEFINITION => VariableDefinitionNode::class,
self::VARIABLE => VariableNode::class,
self::SELECTION_SET => SelectionSetNode::class,
self::FIELD => FieldNode::class,
self::ARGUMENT => ArgumentNode::class,
// Fragments
NodeKind::FRAGMENT_SPREAD => FragmentSpreadNode::class,
NodeKind::INLINE_FRAGMENT => InlineFragmentNode::class,
NodeKind::FRAGMENT_DEFINITION => FragmentDefinitionNode::class,
self::FRAGMENT_SPREAD => FragmentSpreadNode::class,
self::INLINE_FRAGMENT => InlineFragmentNode::class,
self::FRAGMENT_DEFINITION => FragmentDefinitionNode::class,
// Values
NodeKind::INT => IntValueNode::class,
NodeKind::FLOAT => FloatValueNode::class,
NodeKind::STRING => StringValueNode::class,
NodeKind::BOOLEAN => BooleanValueNode::class,
NodeKind::ENUM => EnumValueNode::class,
NodeKind::NULL => NullValueNode::class,
NodeKind::LST => ListValueNode::class,
NodeKind::OBJECT => ObjectValueNode::class,
NodeKind::OBJECT_FIELD => ObjectFieldNode::class,
self::INT => IntValueNode::class,
self::FLOAT => FloatValueNode::class,
self::STRING => StringValueNode::class,
self::BOOLEAN => BooleanValueNode::class,
self::ENUM => EnumValueNode::class,
self::NULL => NullValueNode::class,
self::LST => ListValueNode::class,
self::OBJECT => ObjectValueNode::class,
self::OBJECT_FIELD => ObjectFieldNode::class,
// Directives
NodeKind::DIRECTIVE => DirectiveNode::class,
self::DIRECTIVE => DirectiveNode::class,
// Types
NodeKind::NAMED_TYPE => NamedTypeNode::class,
NodeKind::LIST_TYPE => ListTypeNode::class,
NodeKind::NON_NULL_TYPE => NonNullTypeNode::class,
self::NAMED_TYPE => NamedTypeNode::class,
self::LIST_TYPE => ListTypeNode::class,
self::NON_NULL_TYPE => NonNullTypeNode::class,
// Type System Definitions
NodeKind::SCHEMA_DEFINITION => SchemaDefinitionNode::class,
NodeKind::OPERATION_TYPE_DEFINITION => OperationTypeDefinitionNode::class,
self::SCHEMA_DEFINITION => SchemaDefinitionNode::class,
self::OPERATION_TYPE_DEFINITION => OperationTypeDefinitionNode::class,
// Type Definitions
NodeKind::SCALAR_TYPE_DEFINITION => ScalarTypeDefinitionNode::class,
NodeKind::OBJECT_TYPE_DEFINITION => ObjectTypeDefinitionNode::class,
NodeKind::FIELD_DEFINITION => FieldDefinitionNode::class,
NodeKind::INPUT_VALUE_DEFINITION => InputValueDefinitionNode::class,
NodeKind::INTERFACE_TYPE_DEFINITION => InterfaceTypeDefinitionNode::class,
NodeKind::UNION_TYPE_DEFINITION => UnionTypeDefinitionNode::class,
NodeKind::ENUM_TYPE_DEFINITION => EnumTypeDefinitionNode::class,
NodeKind::ENUM_VALUE_DEFINITION => EnumValueDefinitionNode::class,
NodeKind::INPUT_OBJECT_TYPE_DEFINITION =>InputObjectTypeDefinitionNode::class,
self::SCALAR_TYPE_DEFINITION => ScalarTypeDefinitionNode::class,
self::OBJECT_TYPE_DEFINITION => ObjectTypeDefinitionNode::class,
self::FIELD_DEFINITION => FieldDefinitionNode::class,
self::INPUT_VALUE_DEFINITION => InputValueDefinitionNode::class,
self::INTERFACE_TYPE_DEFINITION => InterfaceTypeDefinitionNode::class,
self::UNION_TYPE_DEFINITION => UnionTypeDefinitionNode::class,
self::ENUM_TYPE_DEFINITION => EnumTypeDefinitionNode::class,
self::ENUM_VALUE_DEFINITION => EnumValueDefinitionNode::class,
self::INPUT_OBJECT_TYPE_DEFINITION => InputObjectTypeDefinitionNode::class,
// Type Extensions
NodeKind::TYPE_EXTENSION_DEFINITION => TypeExtensionDefinitionNode::class,
self::SCALAR_TYPE_EXTENSION => ScalarTypeExtensionNode::class,
self::OBJECT_TYPE_EXTENSION => ObjectTypeExtensionNode::class,
self::INTERFACE_TYPE_EXTENSION => InterfaceTypeExtensionNode::class,
self::UNION_TYPE_EXTENSION => UnionTypeExtensionNode::class,
self::ENUM_TYPE_EXTENSION => EnumTypeExtensionNode::class,
self::INPUT_OBJECT_TYPE_EXTENSION => InputObjectTypeExtensionNode::class,
// Directive Definitions
NodeKind::DIRECTIVE_DEFINITION => DirectiveDefinitionNode::class
self::DIRECTIVE_DEFINITION => DirectiveDefinitionNode::class,
];
}
+74 -43
View File
@@ -1,32 +1,48 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
use ArrayAccess;
use Countable;
use GraphQL\Utils\AST;
use InvalidArgumentException;
use IteratorAggregate;
use Traversable;
use function array_merge;
use function array_splice;
use function count;
use function is_array;
/**
* Class NodeList
*
* @package GraphQL\Utils
* @template T of Node
* @phpstan-implements ArrayAccess<int|string, T>
* @phpstan-implements IteratorAggregate<T>
*/
class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable
class NodeList implements ArrayAccess, IteratorAggregate, Countable
{
/**
* @var array
* @var Node[]
* @phpstan-var array<T>
*/
private $nodes;
/**
* @param array $nodes
* @return static
* @param Node[] $nodes
*
* @phpstan-param array<T> $nodes
* @phpstan-return self<T>
*/
public static function create(array $nodes)
public static function create(array $nodes) : self
{
return new static($nodes);
}
/**
* NodeList constructor.
* @param array $nodes
* @param Node[] $nodes
*
* @phpstan-param array<T> $nodes
*/
public function __construct(array $nodes)
{
@@ -34,87 +50,102 @@ class NodeList implements \ArrayAccess, \IteratorAggregate, \Countable
}
/**
* @param mixed $offset
* @return bool
* @param int|string $offset
*/
public function offsetExists($offset)
public function offsetExists($offset) : bool
{
return isset($this->nodes[$offset]);
}
/**
* @param mixed $offset
* @return mixed
* TODO enable strict typing by changing how the Visitor deals with NodeList.
* Ideally, this function should always return a Node instance.
* However, the Visitor currently allows mutation of the NodeList
* and puts arbitrary values in the NodeList, such as strings.
* We will have to switch to using an array or a less strict
* type instead so we can enable strict typing in this class.
*
* @param int|string $offset
*
* @phpstan-return T
*/
public function offsetGet($offset)
public function offsetGet($offset)// : Node
{
$item = $this->nodes[$offset];
if (is_array($item) && isset($item['kind'])) {
$this->nodes[$offset] = $item = AST::fromArray($item);
/** @phpstan-var T $node */
$node = AST::fromArray($item);
$this->nodes[$offset] = $node;
}
return $item;
return $this->nodes[$offset];
}
/**
* @param mixed $offset
* @param mixed $value
* @param int|string|null $offset
* @param Node|mixed[] $value
*
* @phpstan-param T|mixed[] $value
*/
public function offsetSet($offset, $value)
public function offsetSet($offset, $value) : void
{
if (is_array($value) && isset($value['kind'])) {
if (is_array($value)) {
/** @phpstan-var T $value */
$value = AST::fromArray($value);
}
// Happens when a Node is pushed via []=
if ($offset === null) {
$this->nodes[] = $value;
return;
}
$this->nodes[$offset] = $value;
}
/**
* @param mixed $offset
* @param int|string $offset
*/
public function offsetUnset($offset)
public function offsetUnset($offset) : void
{
unset($this->nodes[$offset]);
}
/**
* @param int $offset
* @param int $length
* @param mixed $replacement
* @return NodeList
*
* @phpstan-return NodeList<T>
*/
public function splice($offset, $length, $replacement = null)
public function splice(int $offset, int $length, $replacement = null) : NodeList
{
return new NodeList(array_splice($this->nodes, $offset, $length, $replacement));
}
/**
* @param $list
* @return NodeList
* @param NodeList|Node[] $list
*
* @phpstan-param NodeList<T>|array<T> $list
* @phpstan-return NodeList<T>
*/
public function merge($list)
public function merge($list) : NodeList
{
if ($list instanceof NodeList) {
if ($list instanceof self) {
$list = $list->nodes;
}
return new NodeList(array_merge($this->nodes, $list));
}
/**
* @return \Generator
*/
public function getIterator()
public function getIterator() : Traversable
{
$count = count($this->nodes);
for ($i = 0; $i < $count; $i++) {
yield $this->offsetGet($i);
foreach ($this->nodes as $key => $_) {
yield $this->offsetGet($key);
}
}
/**
* @return int
*/
public function count()
public function count() : int
{
return count($this->nodes);
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class NonNullTypeNode extends Node implements TypeNode
{
/** @var string */
public $kind = NodeKind::NON_NULL_TYPE;
/**
* @var NameNode | ListTypeNode
*/
/** @var NamedTypeNode|ListTypeNode */
public $type;
}
@@ -1,7 +1,11 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class NullValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::NULL;
}
@@ -1,18 +1,17 @@
<?php
namespace GraphQL\Language\AST;
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ObjectFieldNode extends Node
{
/** @var string */
public $kind = NodeKind::OBJECT_FIELD;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var ValueNode
*/
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode */
public $value;
}
@@ -1,35 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ObjectTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::OBJECT_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var NamedTypeNode[]
*/
public $interfaces = [];
/** @var NodeList<NamedTypeNode> */
public $interfaces;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var FieldDefinitionNode[]
*/
/** @var NodeList<FieldDefinitionNode> */
public $fields;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ObjectTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::OBJECT_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<NamedTypeNode> */
public $interfaces;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<FieldDefinitionNode> */
public $fields;
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ObjectValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::OBJECT;
/**
* @var ObjectFieldNode[]
*/
/** @var NodeList<ObjectFieldNode> */
public $fields;
}
@@ -1,35 +1,26 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class OperationDefinitionNode extends Node implements DefinitionNode, HasSelectionSet
class OperationDefinitionNode extends Node implements ExecutableDefinitionNode, HasSelectionSet
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::OPERATION_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode|null */
public $name;
/**
* @var string (oneOf 'query', 'mutation'))
*/
/** @var string (oneOf 'query', 'mutation', 'subscription')) */
public $operation;
/**
* @var VariableDefinitionNode[]
*/
/** @var NodeList<VariableDefinitionNode> */
public $variableDefinitions;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var SelectionSetNode
*/
/** @var SelectionSetNode */
public $selectionSet;
}
@@ -1,11 +1,12 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class OperationTypeDefinitionNode extends Node
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::OPERATION_TYPE_DEFINITION;
/**
@@ -15,8 +16,6 @@ class OperationTypeDefinitionNode extends Node
*/
public $operation;
/**
* @var NamedTypeNode
*/
/** @var NamedTypeNode */
public $type;
}
@@ -1,25 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ScalarTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::SCALAR_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class ScalarTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::SCALAR_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<DirectiveNode> */
public $directives;
}
@@ -1,20 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class SchemaDefinitionNode extends Node implements TypeSystemDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::SCHEMA_DEFINITION;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var OperationTypeDefinitionNode[]
*/
/** @var NodeList<OperationTypeDefinitionNode> */
public $operationTypes;
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class SchemaTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::SCHEMA_EXTENSION;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<OperationTypeDefinitionNode> */
public $operationTypes;
}
@@ -1,9 +1,12 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
interface SelectionNode
{
/**
* export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode
*/
interface SelectionNode
{
}
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class SelectionSetNode extends Node
{
/** @var string */
public $kind = NodeKind::SELECTION_SET;
/**
* @var SelectionNode[]
*/
/** @var NodeList<SelectionNode&Node> */
public $selections;
}
@@ -1,12 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class StringValueNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::STRING;
/**
* @var string
*/
/** @var string */
public $value;
/** @var bool */
public $block;
}
@@ -1,14 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type TypeDefinitionNode = ScalarTypeDefinitionNode
* | ObjectTypeDefinitionNode
* | InterfaceTypeDefinitionNode
* | UnionTypeDefinitionNode
* | EnumTypeDefinitionNode
* | InputObjectTypeDefinitionNode
*/
interface TypeDefinitionNode extends TypeSystemDefinitionNode
{
/**
export type TypeDefinitionNode = ScalarTypeDefinitionNode
| ObjectTypeDefinitionNode
| InterfaceTypeDefinitionNode
| UnionTypeDefinitionNode
| EnumTypeDefinitionNode
| InputObjectTypeDefinitionNode
*/
}
@@ -1,15 +0,0 @@
<?php
namespace GraphQL\Language\AST;
class TypeExtensionDefinitionNode extends Node implements TypeSystemDefinitionNode
{
/**
* @var string
*/
public $kind = NodeKind::TYPE_EXTENSION_DEFINITION;
/**
* @var ObjectTypeDefinitionNode
*/
public $definition;
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type TypeExtensionNode =
* | ScalarTypeExtensionNode
* | ObjectTypeExtensionNode
* | InterfaceTypeExtensionNode
* | UnionTypeExtensionNode
* | EnumTypeExtensionNode
* | InputObjectTypeExtensionNode;
*/
interface TypeExtensionNode extends TypeSystemDefinitionNode
{
}
+8 -7
View File
@@ -1,13 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type TypeNode = NamedTypeNode
* | ListTypeNode
* | NonNullTypeNode
*/
interface TypeNode
{
/**
export type TypeNode = NamedTypeNode
| ListTypeNode
| NonNullTypeNode
*/
}
@@ -1,12 +1,18 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
* export type TypeSystemDefinitionNode =
* | SchemaDefinitionNode
* | TypeDefinitionNode
* | TypeExtensionNode
* | DirectiveDefinitionNode
*
* @property NameNode $name
*/
interface TypeSystemDefinitionNode extends DefinitionNode
{
/**
export type TypeSystemDefinitionNode = SchemaDefinitionNode
| TypeDefinitionNode
| TypeExtensionDefinitionNode
| DirectiveDefinitionNode
*/
}
@@ -1,30 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class UnionTypeDefinitionNode extends Node implements TypeDefinitionNode
{
/**
* @var string
*/
/** @var string */
public $kind = NodeKind::UNION_TYPE_DEFINITION;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
/**
* @var DirectiveNode[]
*/
/** @var NodeList<DirectiveNode> */
public $directives;
/**
* @var NamedTypeNode[]
*/
public $types = [];
/** @var NodeList<NamedTypeNode> */
public $types;
/**
* @var string
*/
/** @var StringValueNode|null */
public $description;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class UnionTypeExtensionNode extends Node implements TypeExtensionNode
{
/** @var string */
public $kind = NodeKind::UNION_TYPE_EXTENSION;
/** @var NameNode */
public $name;
/** @var NodeList<DirectiveNode> */
public $directives;
/** @var NodeList<NamedTypeNode> */
public $types;
}
+4 -1
View File
@@ -1,8 +1,12 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
/**
export type ValueNode = VariableNode
| NullValueNode
| IntValueNode
| FloatValueNode
| StringValueNode
@@ -13,5 +17,4 @@ export type ValueNode = VariableNode
*/
interface ValueNode
{
}
@@ -1,22 +1,23 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class VariableDefinitionNode extends Node implements DefinitionNode
{
/** @var string */
public $kind = NodeKind::VARIABLE_DEFINITION;
/**
* @var VariableNode
*/
/** @var VariableNode */
public $variable;
/**
* @var TypeNode
*/
/** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */
public $type;
/**
* @var ValueNode|null
*/
/** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null */
public $defaultValue;
/** @var NodeList<DirectiveNode> */
public $directives;
}
+6 -4
View File
@@ -1,12 +1,14 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language\AST;
class VariableNode extends Node
class VariableNode extends Node implements ValueNode
{
/** @var string */
public $kind = NodeKind::VARIABLE;
/**
* @var NameNode
*/
/** @var NameNode */
public $name;
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
/**
* List of available directive locations
*/
class DirectiveLocation
{
// Request Definitions
const QUERY = 'QUERY';
const MUTATION = 'MUTATION';
const SUBSCRIPTION = 'SUBSCRIPTION';
const FIELD = 'FIELD';
const FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION';
const FRAGMENT_SPREAD = 'FRAGMENT_SPREAD';
const INLINE_FRAGMENT = 'INLINE_FRAGMENT';
const VARIABLE_DEFINITION = 'VARIABLE_DEFINITION';
// Type System Definitions
const SCHEMA = 'SCHEMA';
const SCALAR = 'SCALAR';
const OBJECT = 'OBJECT';
const FIELD_DEFINITION = 'FIELD_DEFINITION';
const ARGUMENT_DEFINITION = 'ARGUMENT_DEFINITION';
const IFACE = 'INTERFACE';
const UNION = 'UNION';
const ENUM = 'ENUM';
const ENUM_VALUE = 'ENUM_VALUE';
const INPUT_OBJECT = 'INPUT_OBJECT';
const INPUT_FIELD_DEFINITION = 'INPUT_FIELD_DEFINITION';
/** @var string[] */
private static $locations = [
self::QUERY => self::QUERY,
self::MUTATION => self::MUTATION,
self::SUBSCRIPTION => self::SUBSCRIPTION,
self::FIELD => self::FIELD,
self::FRAGMENT_DEFINITION => self::FRAGMENT_DEFINITION,
self::FRAGMENT_SPREAD => self::FRAGMENT_SPREAD,
self::INLINE_FRAGMENT => self::INLINE_FRAGMENT,
self::SCHEMA => self::SCHEMA,
self::SCALAR => self::SCALAR,
self::OBJECT => self::OBJECT,
self::FIELD_DEFINITION => self::FIELD_DEFINITION,
self::ARGUMENT_DEFINITION => self::ARGUMENT_DEFINITION,
self::IFACE => self::IFACE,
self::UNION => self::UNION,
self::ENUM => self::ENUM,
self::ENUM_VALUE => self::ENUM_VALUE,
self::INPUT_OBJECT => self::INPUT_OBJECT,
self::INPUT_FIELD_DEFINITION => self::INPUT_FIELD_DEFINITION,
];
public static function has(string $name) : bool
{
return isset(self::$locations[$name]);
}
}
+400 -186
View File
@@ -1,8 +1,19 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
use GraphQL\Error\SyntaxError;
use GraphQL\Utils\BlockString;
use GraphQL\Utils\Utils;
use function chr;
use function hexdec;
use function mb_convert_encoding;
use function ord;
use function pack;
use function preg_match;
use function substr;
/**
* A Lexer is a stateful stream generator in that every time
@@ -15,14 +26,26 @@ use GraphQL\Utils\Utils;
*/
class Lexer
{
/**
* @var Source
*/
private const TOKEN_BANG = 33;
private const TOKEN_HASH = 35;
private const TOKEN_DOLLAR = 36;
private const TOKEN_AMP = 38;
private const TOKEN_PAREN_L = 40;
private const TOKEN_PAREN_R = 41;
private const TOKEN_DOT = 46;
private const TOKEN_COLON = 58;
private const TOKEN_EQUALS = 61;
private const TOKEN_AT = 64;
private const TOKEN_BRACKET_L = 91;
private const TOKEN_BRACKET_R = 93;
private const TOKEN_BRACE_L = 123;
private const TOKEN_PIPE = 124;
private const TOKEN_BRACE_R = 125;
/** @var Source */
public $source;
/**
* @var array
*/
/** @var bool[] */
public $options;
/**
@@ -68,22 +91,19 @@ class Lexer
private $byteStreamPosition;
/**
* Lexer constructor.
*
* @param Source $source
* @param array $options
* @param bool[] $options
*/
public function __construct(Source $source, array $options = [])
{
$startOfFileToken = new Token(Token::SOF, 0, 0, 0, 0, null);
$this->source = $source;
$this->options = $options;
$this->source = $source;
$this->options = $options;
$this->lastToken = $startOfFileToken;
$this->token = $startOfFileToken;
$this->line = 1;
$this->token = $startOfFileToken;
$this->line = 1;
$this->lineStart = 0;
$this->position = $this->byteStreamPosition = 0;
$this->position = $this->byteStreamPosition = 0;
}
/**
@@ -91,29 +111,26 @@ class Lexer
*/
public function advance()
{
$token = $this->lastToken = $this->token;
$this->lastToken = $this->token;
return $this->token = $this->lookahead();
}
public function lookahead()
{
$token = $this->token;
if ($token->kind !== Token::EOF) {
do {
$token = $token->next = $this->readToken($token);
$token = $token->next ?? ($token->next = $this->readToken($token));
} while ($token->kind === Token::COMMENT);
$this->token = $token;
}
return $token;
}
/**
* @return Token
*/
public function nextToken()
{
trigger_error(__METHOD__ . ' is deprecated in favor of advance()', E_USER_DEPRECATED);
return $this->advance();
}
/**
* @param Token $prev
* @return Token
*
* @throws SyntaxError
*/
private function readToken(Token $prev)
@@ -124,98 +141,166 @@ class Lexer
$position = $this->position;
$line = $this->line;
$col = 1 + $position - $this->lineStart;
$col = 1 + $position - $this->lineStart;
if ($position >= $bodyLength) {
return new Token(Token::EOF, $bodyLength, $bodyLength, $line, $col, $prev);
}
// Read next char and advance string cursor:
list (, $code, $bytes) = $this->readChar(true);
// SourceCharacter
if ($code < 0x0020 && $code !== 0x0009 && $code !== 0x000A && $code !== 0x000D) {
throw new SyntaxError(
$this->source,
$position,
'Cannot contain the invalid character ' . Utils::printCharCode($code)
);
}
[, $code, $bytes] = $this->readChar(true);
switch ($code) {
case 33: // !
case self::TOKEN_BANG:
return new Token(Token::BANG, $position, $position + 1, $line, $col, $prev);
case 35: // #
case self::TOKEN_HASH: // #
$this->moveStringCursor(-1, -1 * $bytes);
return $this->readComment($line, $col, $prev);
case 36: // $
return new Token(Token::DOLLAR, $position, $position + 1, $line, $col, $prev);
case 40: // (
return new Token(Token::PAREN_L, $position, $position + 1, $line, $col, $prev);
case 41: // )
return new Token(Token::PAREN_R, $position, $position + 1, $line, $col, $prev);
case 46: // .
list (, $charCode1) = $this->readChar(true);
list (, $charCode2) = $this->readChar(true);
if ($charCode1 === 46 && $charCode2 === 46) {
return $this->readComment($line, $col, $prev);
case self::TOKEN_DOLLAR:
return new Token(Token::DOLLAR, $position, $position + 1, $line, $col, $prev);
case self::TOKEN_AMP:
return new Token(Token::AMP, $position, $position + 1, $line, $col, $prev);
case self::TOKEN_PAREN_L:
return new Token(Token::PAREN_L, $position, $position + 1, $line, $col, $prev);
case self::TOKEN_PAREN_R:
return new Token(Token::PAREN_R, $position, $position + 1, $line, $col, $prev);
case self::TOKEN_DOT: // .
[, $charCode1] = $this->readChar(true);
[, $charCode2] = $this->readChar(true);
if ($charCode1 === self::TOKEN_DOT && $charCode2 === self::TOKEN_DOT) {
return new Token(Token::SPREAD, $position, $position + 3, $line, $col, $prev);
}
break;
case 58: // :
case self::TOKEN_COLON:
return new Token(Token::COLON, $position, $position + 1, $line, $col, $prev);
case 61: // =
case self::TOKEN_EQUALS:
return new Token(Token::EQUALS, $position, $position + 1, $line, $col, $prev);
case 64: // @
case self::TOKEN_AT:
return new Token(Token::AT, $position, $position + 1, $line, $col, $prev);
case 91: // [
case self::TOKEN_BRACKET_L:
return new Token(Token::BRACKET_L, $position, $position + 1, $line, $col, $prev);
case 93: // ]
case self::TOKEN_BRACKET_R:
return new Token(Token::BRACKET_R, $position, $position + 1, $line, $col, $prev);
case 123: // {
case self::TOKEN_BRACE_L:
return new Token(Token::BRACE_L, $position, $position + 1, $line, $col, $prev);
case 124: // |
case self::TOKEN_PIPE:
return new Token(Token::PIPE, $position, $position + 1, $line, $col, $prev);
case 125: // }
case self::TOKEN_BRACE_R:
return new Token(Token::BRACE_R, $position, $position + 1, $line, $col, $prev);
// A-Z
case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72:
case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80:
case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88:
case 89: case 90:
// _
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
case 76:
case 77:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
// _
case 95:
// a-z
case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104:
case 105: case 106: case 107: case 108: case 109: case 110: case 111:
case 112: case 113: case 114: case 115: case 116: case 117: case 118:
case 119: case 120: case 121: case 122:
// a-z
case 97:
case 98:
case 99:
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 106:
case 107:
case 108:
case 109:
case 110:
case 111:
case 112:
case 113:
case 114:
case 115:
case 116:
case 117:
case 118:
case 119:
case 120:
case 121:
case 122:
return $this->moveStringCursor(-1, -1 * $bytes)
->readName($line, $col, $prev);
// -
case 45:
// 0-9
case 48: case 49: case 50: case 51: case 52:
case 53: case 54: case 55: case 56: case 57:
// 0-9
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return $this->moveStringCursor(-1, -1 * $bytes)
->readNumber($line, $col, $prev);
// "
case 34:
return $this->moveStringCursor(-1, -1 * $bytes)
[, $nextCode] = $this->readChar();
[, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar();
if ($nextCode === 34 && $nextNextCode === 34) {
return $this->moveStringCursor(-2, (-1 * $bytes) - 1)
->readBlockString($line, $col, $prev);
}
return $this->moveStringCursor(-2, (-1 * $bytes) - 1)
->readString($line, $col, $prev);
}
$errMessage = $code === 39
? "Unexpected single quote character ('), did you mean to use ". 'a double quote (")?'
: 'Cannot parse the unexpected character ' . Utils::printCharCode($code) . '.';
throw new SyntaxError(
$this->source,
$position,
$errMessage
$this->unexpectedCharacterMessage($code)
);
}
private function unexpectedCharacterMessage($code)
{
// SourceCharacter
if ($code < 0x0020 && $code !== 0x0009 && $code !== 0x000A && $code !== 0x000D) {
return 'Cannot contain the invalid character ' . Utils::printCharCode($code);
}
if ($code === 39) {
return "Unexpected single quote character ('), did you mean to use " .
'a double quote (")?';
}
return 'Cannot parse the unexpected character ' . Utils::printCharCode($code) . '.';
}
/**
* Reads an alphanumeric + underscore name from the source.
*
@@ -223,24 +308,25 @@ class Lexer
*
* @param int $line
* @param int $col
* @param Token $prev
*
* @return Token
*/
private function readName($line, $col, Token $prev)
{
$value = '';
$start = $this->position;
list ($char, $code) = $this->readChar();
$value = '';
$start = $this->position;
[$char, $code] = $this->readChar();
while ($code && (
$code === 95 || // _
$code >= 48 && $code <= 57 || // 0-9
$code >= 65 && $code <= 90 || // A-Z
$code >= 97 && $code <= 122 // a-z
)) {
$value .= $char;
list ($char, $code) = $this->moveStringCursor(1, 1)->readChar();
while ($code !== null && (
$code === 95 || // _
($code >= 48 && $code <= 57) || // 0-9
($code >= 65 && $code <= 90) || // A-Z
($code >= 97 && $code <= 122) // a-z
)) {
$value .= $char;
[$char, $code] = $this->moveStringCursor(1, 1)->readChar();
}
return new Token(
Token::NAME,
$start,
@@ -261,49 +347,54 @@ class Lexer
*
* @param int $line
* @param int $col
* @param Token $prev
*
* @return Token
*
* @throws SyntaxError
*/
private function readNumber($line, $col, Token $prev)
{
$value = '';
$start = $this->position;
list ($char, $code) = $this->readChar();
$value = '';
$start = $this->position;
[$char, $code] = $this->readChar();
$isFloat = false;
if ($code === 45) { // -
$value .= $char;
list ($char, $code) = $this->moveStringCursor(1, 1)->readChar();
$value .= $char;
[$char, $code] = $this->moveStringCursor(1, 1)->readChar();
}
// guard against leading zero's
if ($code === 48) { // 0
$value .= $char;
list ($char, $code) = $this->moveStringCursor(1, 1)->readChar();
$value .= $char;
[$char, $code] = $this->moveStringCursor(1, 1)->readChar();
if ($code >= 48 && $code <= 57) {
throw new SyntaxError($this->source, $this->position, "Invalid number, unexpected digit after 0: " . Utils::printCharCode($code));
throw new SyntaxError(
$this->source,
$this->position,
'Invalid number, unexpected digit after 0: ' . Utils::printCharCode($code)
);
}
} else {
$value .= $this->readDigits();
list ($char, $code) = $this->readChar();
$value .= $this->readDigits();
[$char, $code] = $this->readChar();
}
if ($code === 46) { // .
$isFloat = true;
$this->moveStringCursor(1, 1);
$value .= $char;
$value .= $this->readDigits();
list ($char, $code) = $this->readChar();
$value .= $char;
$value .= $this->readDigits();
[$char, $code] = $this->readChar();
}
if ($code === 69 || $code === 101) { // E e
$isFloat = true;
$value .= $char;
list ($char, $code) = $this->moveStringCursor(1, 1)->readChar();
$isFloat = true;
$value .= $char;
[$char, $code] = $this->moveStringCursor(1, 1)->readChar();
if ($code === 43 || $code === 45) { // + -
$value .= $char;
@@ -328,14 +419,14 @@ class Lexer
*/
private function readDigits()
{
list ($char, $code) = $this->readChar();
[$char, $code] = $this->readChar();
if ($code >= 48 && $code <= 57) { // 0 - 9
$value = '';
do {
$value .= $char;
list ($char, $code) = $this->moveStringCursor(1, 1)->readChar();
$value .= $char;
[$char, $code] = $this->moveStringCursor(1, 1)->readChar();
} while ($code >= 48 && $code <= 57); // 0 - 9
return $value;
@@ -355,8 +446,9 @@ class Lexer
/**
* @param int $line
* @param int $col
* @param Token $prev
*
* @return Token
*
* @throws SyntaxError
*/
private function readString($line, $col, Token $prev)
@@ -364,46 +456,96 @@ class Lexer
$start = $this->position;
// Skip leading quote and read first string char:
list ($char, $code, $bytes) = $this->moveStringCursor(1, 1)->readChar();
[$char, $code, $bytes] = $this->moveStringCursor(1, 1)->readChar();
$chunk = '';
$value = '';
while (
$code &&
while ($code !== null &&
// not LineTerminator
$code !== 10 && $code !== 13 &&
// not Quote (")
$code !== 34
$code !== 10 && $code !== 13
) {
// Closing Quote (")
if ($code === 34) {
$value .= $chunk;
// Skip quote
$this->moveStringCursor(1, 1);
return new Token(
Token::STRING,
$start,
$this->position,
$line,
$col,
$prev,
$value
);
}
$this->assertValidStringCharacterCode($code, $this->position);
$this->moveStringCursor(1, $bytes);
if ($code === 92) { // \
$value .= $chunk;
list (, $code) = $this->readChar(true);
$value .= $chunk;
[, $code] = $this->readChar(true);
switch ($code) {
case 34: $value .= '"'; break;
case 47: $value .= '/'; break;
case 92: $value .= '\\'; break;
case 98: $value .= chr(8); break; // \b (backspace)
case 102: $value .= "\f"; break;
case 110: $value .= "\n"; break;
case 114: $value .= "\r"; break;
case 116: $value .= "\t"; break;
case 34:
$value .= '"';
break;
case 47:
$value .= '/';
break;
case 92:
$value .= '\\';
break;
case 98:
$value .= chr(8);
break; // \b (backspace)
case 102:
$value .= "\f";
break;
case 110:
$value .= "\n";
break;
case 114:
$value .= "\r";
break;
case 116:
$value .= "\t";
break;
case 117:
$position = $this->position;
list ($hex) = $this->readChars(4, true);
if (!preg_match('/[0-9a-fA-F]{4}/', $hex)) {
[$hex] = $this->readChars(4, true);
if (! preg_match('/[0-9a-fA-F]{4}/', $hex)) {
throw new SyntaxError(
$this->source,
$position - 1,
'Invalid character escape sequence: \\u' . $hex
);
}
$code = hexdec($hex);
// UTF-16 surrogate pair detection and handling.
$highOrderByte = $code >> 8;
if (0xD8 <= $highOrderByte && $highOrderByte <= 0xDF) {
[$utf16Continuation] = $this->readChars(6, true);
if (! preg_match('/^\\\u[0-9a-fA-F]{4}$/', $utf16Continuation)) {
throw new SyntaxError(
$this->source,
$this->position - 5,
'Invalid UTF-16 trailing surrogate: ' . $utf16Continuation
);
}
$surrogatePairHex = $hex . substr($utf16Continuation, 2, 4);
$value .= mb_convert_encoding(pack('H*', $surrogatePairHex), 'UTF-8', 'UTF-16');
break;
}
$this->assertValidStringCharacterCode($code, $position - 2);
$value .= Utils::chr($code);
break;
default:
@@ -418,30 +560,86 @@ class Lexer
$chunk .= $char;
}
list ($char, $code, $bytes) = $this->readChar();
[$char, $code, $bytes] = $this->readChar();
}
if ($code !== 34) {
throw new SyntaxError(
$this->source,
$this->position,
'Unterminated string.'
);
}
$value .= $chunk;
// Skip trailing quote:
$this->moveStringCursor(1, 1);
return new Token(
Token::STRING,
$start,
throw new SyntaxError(
$this->source,
$this->position,
$line,
$col,
$prev,
$value
'Unterminated string.'
);
}
/**
* Reads a block string token from the source file.
*
* """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
*/
private function readBlockString($line, $col, Token $prev)
{
$start = $this->position;
// Skip leading quotes and read first string char:
[$char, $code, $bytes] = $this->moveStringCursor(3, 3)->readChar();
$chunk = '';
$value = '';
while ($code !== null) {
// Closing Triple-Quote (""")
if ($code === 34) {
// Move 2 quotes
[, $nextCode] = $this->moveStringCursor(1, 1)->readChar();
[, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar();
if ($nextCode === 34 && $nextNextCode === 34) {
$value .= $chunk;
$this->moveStringCursor(1, 1);
return new Token(
Token::BLOCK_STRING,
$start,
$this->position,
$line,
$col,
$prev,
BlockString::value($value)
);
}
// move cursor back to before the first quote
$this->moveStringCursor(-2, -2);
}
$this->assertValidBlockStringCharacterCode($code, $this->position);
$this->moveStringCursor(1, $bytes);
[, $nextCode] = $this->readChar();
[, $nextNextCode] = $this->moveStringCursor(1, 1)->readChar();
[, $nextNextNextCode] = $this->moveStringCursor(1, 1)->readChar();
// Escape Triple-Quote (\""")
if ($code === 92 &&
$nextCode === 34 &&
$nextNextCode === 34 &&
$nextNextNextCode === 34
) {
$this->moveStringCursor(1, 1);
$value .= $chunk . '"""';
$chunk = '';
} else {
$this->moveStringCursor(-2, -2);
$chunk .= $char;
}
[$char, $code, $bytes] = $this->readChar();
}
throw new SyntaxError(
$this->source,
$this->position,
'Unterminated string.'
);
}
@@ -457,6 +655,18 @@ class Lexer
}
}
private function assertValidBlockStringCharacterCode($code, $position)
{
// SourceCharacter
if ($code < 0x0020 && $code !== 0x0009 && $code !== 0x000A && $code !== 0x000D) {
throw new SyntaxError(
$this->source,
$position,
'Invalid character within String: ' . Utils::printCharCode($code)
);
}
}
/**
* Reads from body starting at startPosition until it finds a non-whitespace
* or commented character, then places cursor to the position of that character.
@@ -464,18 +674,18 @@ class Lexer
private function positionAfterWhitespace()
{
while ($this->position < $this->source->length) {
list(, $code, $bytes) = $this->readChar();
[, $code, $bytes] = $this->readChar();
// Skip whitespace
// tab | space | comma | BOM
if ($code === 9 || $code === 32 || $code === 44 || $code === 0xFEFF) {
$this->moveStringCursor(1, $bytes);
} else if ($code === 10) { // new line
} elseif ($code === 10) { // new line
$this->moveStringCursor(1, $bytes);
$this->line++;
$this->lineStart = $this->position;
} else if ($code === 13) { // carriage return
list(, $nextCode, $nextBytes) = $this->moveStringCursor(1, $bytes)->readChar();
} elseif ($code === 13) { // carriage return
[, $nextCode, $nextBytes] = $this->moveStringCursor(1, $bytes)->readChar();
if ($nextCode === 10) { // lf after cr
$this->moveStringCursor(1, $nextBytes);
@@ -493,9 +703,9 @@ class Lexer
*
* #[\u0009\u0020-\uFFFF]*
*
* @param $line
* @param $col
* @param Token $prev
* @param int $line
* @param int $col
*
* @return Token
*/
private function readComment($line, $col, Token $prev)
@@ -505,12 +715,11 @@ class Lexer
$bytes = 1;
do {
list ($char, $code, $bytes) = $this->moveStringCursor(1, $bytes)->readChar();
$value .= $char;
} while (
$code &&
// SourceCharacter but not LineTerminator
($code > 0x001F || $code === 0x0009)
[$char, $code, $bytes] = $this->moveStringCursor(1, $bytes)->readChar();
$value .= $char;
} while ($code !== null &&
// SourceCharacter but not LineTerminator
($code > 0x001F || $code === 0x0009)
);
return new Token(
@@ -528,8 +737,9 @@ class Lexer
* Reads next UTF8Character from the byte stream, starting from $byteStreamPosition.
*
* @param bool $advance
* @param int $byteStreamPosition
* @return array
* @param int $byteStreamPosition
*
* @return (string|int)[]
*/
private function readChar($advance = false, $byteStreamPosition = null)
{
@@ -537,9 +747,9 @@ class Lexer
$byteStreamPosition = $this->byteStreamPosition;
}
$code = 0;
$utf8char = '';
$bytes = 0;
$code = null;
$utf8char = '';
$bytes = 0;
$positionOffset = 0;
if (isset($this->source->body[$byteStreamPosition])) {
@@ -547,7 +757,7 @@ class Lexer
if ($ord < 128) {
$bytes = 1;
} else if ($ord < 224) {
} elseif ($ord < 224) {
$bytes = 2;
} elseif ($ord < 240) {
$bytes = 3;
@@ -560,7 +770,7 @@ class Lexer
$utf8char .= $this->source->body[$pos];
}
$positionOffset = 1;
$code = $bytes === 1 ? $ord : Utils::ord($utf8char);
$code = $bytes === 1 ? $ord : Utils::ord($utf8char);
}
if ($advance) {
@@ -573,40 +783,44 @@ class Lexer
/**
* Reads next $numberOfChars UTF8 characters from the byte stream, starting from $byteStreamPosition.
*
* @param $numberOfChars
* @param int $charCount
* @param bool $advance
* @param null $byteStreamPosition
* @return array
*
* @return (string|int)[]
*/
private function readChars($numberOfChars, $advance = false, $byteStreamPosition = null)
private function readChars($charCount, $advance = false, $byteStreamPosition = null)
{
$result = '';
$result = '';
$totalBytes = 0;
$byteOffset = $byteStreamPosition ?: $this->byteStreamPosition;
$byteOffset = $byteStreamPosition ?? $this->byteStreamPosition;
for ($i = 0; $i < $numberOfChars; $i++) {
list ($char, $code, $bytes) = $this->readChar(false, $byteOffset);
$totalBytes += $bytes;
$byteOffset += $bytes;
$result .= $char;
for ($i = 0; $i < $charCount; $i++) {
[$char, $code, $bytes] = $this->readChar(false, $byteOffset);
$totalBytes += $bytes;
$byteOffset += $bytes;
$result .= $char;
}
if ($advance) {
$this->moveStringCursor($numberOfChars, $totalBytes);
$this->moveStringCursor($charCount, $totalBytes);
}
return [$result, $totalBytes];
}
/**
* Moves internal string cursor position
*
* @param $positionOffset
* @param $byteStreamOffset
* @return $this
* @param int $positionOffset
* @param int $byteStreamOffset
*
* @return self
*/
private function moveStringCursor($positionOffset, $byteStreamOffset)
{
$this->position += $positionOffset;
$this->position += $positionOffset;
$this->byteStreamPosition += $byteStreamOffset;
return $this;
}
}
File diff suppressed because it is too large. Load diff
+425 -196
View File
@@ -1,44 +1,63 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
use GraphQL\Language\AST\ArgumentNode;
use GraphQL\Language\AST\DirectiveDefinitionNode;
use GraphQL\Language\AST\EnumTypeDefinitionNode;
use GraphQL\Language\AST\EnumValueDefinitionNode;
use GraphQL\Language\AST\FieldDefinitionNode;
use GraphQL\Language\AST\InputObjectTypeDefinitionNode;
use GraphQL\Language\AST\InputValueDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\DirectiveDefinitionNode;
use GraphQL\Language\AST\DirectiveNode;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\EnumTypeDefinitionNode;
use GraphQL\Language\AST\EnumTypeExtensionNode;
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\FragmentDefinitionNode;
use GraphQL\Language\AST\FragmentSpreadNode;
use GraphQL\Language\AST\InlineFragmentNode;
use GraphQL\Language\AST\InputObjectTypeDefinitionNode;
use GraphQL\Language\AST\InputObjectTypeExtensionNode;
use GraphQL\Language\AST\InputValueDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeExtensionNode;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\ListTypeNode;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\NamedTypeNode;
use GraphQL\Language\AST\NameNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\AST\NonNullTypeNode;
use GraphQL\Language\AST\NullValueNode;
use GraphQL\Language\AST\ObjectFieldNode;
use GraphQL\Language\AST\ObjectTypeDefinitionNode;
use GraphQL\Language\AST\ObjectTypeExtensionNode;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Language\AST\OperationTypeDefinitionNode;
use GraphQL\Language\AST\ScalarTypeDefinitionNode;
use GraphQL\Language\AST\ScalarTypeExtensionNode;
use GraphQL\Language\AST\SchemaDefinitionNode;
use GraphQL\Language\AST\SchemaTypeExtensionNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Language\AST\TypeExtensionDefinitionNode;
use GraphQL\Language\AST\UnionTypeDefinitionNode;
use GraphQL\Language\AST\UnionTypeExtensionNode;
use GraphQL\Language\AST\VariableDefinitionNode;
use GraphQL\Language\AST\VariableNode;
use GraphQL\Utils\Utils;
use function count;
use function implode;
use function json_encode;
use function preg_replace;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
/**
* Prints AST to string. Capable of printing GraphQL queries and Type definition language.
@@ -57,209 +76,401 @@ class Printer
/**
* Prints AST to string. Capable of printing GraphQL queries and Type definition language.
*
* @api
* @param Node $ast
*
* @return string
*
* @api
*/
public static function doPrint($ast)
{
static $instance;
$instance = $instance ?: new static();
$instance = $instance ?? new static();
return $instance->printAST($ast);
}
protected function __construct()
{}
{
}
/**
* Traverse an AST bottom-up, converting all nodes to strings.
*
* That means the AST is manipulated in such a way that it no longer
* resembles the well-formed result of parsing.
*/
public function printAST($ast)
{
return Visitor::visit($ast, [
'leave' => [
NodeKind::NAME => function(Node $node) {
return '' . $node->value;
},
NodeKind::VARIABLE => function($node) {
return '$' . $node->name;
},
NodeKind::DOCUMENT => function(DocumentNode $node) {
return $this->join($node->definitions, "\n\n") . "\n";
},
NodeKind::OPERATION_DEFINITION => function(OperationDefinitionNode $node) {
$op = $node->operation;
$name = $node->name;
$varDefs = $this->wrap('(', $this->join($node->variableDefinitions, ', '), ')');
$directives = $this->join($node->directives, ' ');
$selectionSet = $node->selectionSet;
// Anonymous queries with no directives or variable definitions can use
// the query short form.
return !$name && !$directives && !$varDefs && $op === 'query'
? $selectionSet
: $this->join([$op, $this->join([$name, $varDefs]), $directives, $selectionSet], ' ');
},
NodeKind::VARIABLE_DEFINITION => function(VariableDefinitionNode $node) {
return $node->variable . ': ' . $node->type . $this->wrap(' = ', $node->defaultValue);
},
NodeKind::SELECTION_SET => function(SelectionSetNode $node) {
return $this->block($node->selections);
},
NodeKind::FIELD => function(FieldNode $node) {
return $this->join([
$this->wrap('', $node->alias, ': ') . $node->name . $this->wrap('(', $this->join($node->arguments, ', '), ')'),
$this->join($node->directives, ' '),
$node->selectionSet
], ' ');
},
NodeKind::ARGUMENT => function(ArgumentNode $node) {
return $node->name . ': ' . $node->value;
},
return Visitor::visit(
$ast,
[
'leave' => [
NodeKind::NAME => static function (NameNode $node) : string {
return $node->value;
},
// Fragments
NodeKind::FRAGMENT_SPREAD => function(FragmentSpreadNode $node) {
return '...' . $node->name . $this->wrap(' ', $this->join($node->directives, ' '));
},
NodeKind::INLINE_FRAGMENT => function(InlineFragmentNode $node) {
return $this->join([
"...",
$this->wrap('on ', $node->typeCondition),
$this->join($node->directives, ' '),
$node->selectionSet
], ' ');
},
NodeKind::FRAGMENT_DEFINITION => function(FragmentDefinitionNode $node) {
return "fragment {$node->name} on {$node->typeCondition} "
. $this->wrap('', $this->join($node->directives, ' '), ' ')
. $node->selectionSet;
},
NodeKind::VARIABLE => static function (VariableNode $node) : string {
return '$' . $node->name;
},
// Value
NodeKind::INT => function(IntValueNode $node) {
return $node->value;
},
NodeKind::FLOAT => function(FloatValueNode $node) {
return $node->value;
},
NodeKind::STRING => function(StringValueNode $node) {
return json_encode($node->value);
},
NodeKind::BOOLEAN => function(BooleanValueNode $node) {
return $node->value ? 'true' : 'false';
},
NodeKind::NULL => function(NullValueNode $node) {
return 'null';
},
NodeKind::ENUM => function(EnumValueNode $node) {
return $node->value;
},
NodeKind::LST => function(ListValueNode $node) {
return '[' . $this->join($node->values, ', ') . ']';
},
NodeKind::OBJECT => function(ObjectValueNode $node) {
return '{' . $this->join($node->fields, ', ') . '}';
},
NodeKind::OBJECT_FIELD => function(ObjectFieldNode $node) {
return $node->name . ': ' . $node->value;
},
NodeKind::DOCUMENT => function (DocumentNode $node) : string {
return $this->join($node->definitions, "\n\n") . "\n";
},
// DirectiveNode
NodeKind::DIRECTIVE => function(DirectiveNode $node) {
return '@' . $node->name . $this->wrap('(', $this->join($node->arguments, ', '), ')');
},
NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) : string {
$op = $node->operation;
$name = $node->name;
$varDefs = $this->wrap('(', $this->join($node->variableDefinitions, ', '), ')');
$directives = $this->join($node->directives, ' ');
$selectionSet = $node->selectionSet;
// Type
NodeKind::NAMED_TYPE => function(NamedTypeNode $node) {
return $node->name;
},
NodeKind::LIST_TYPE => function(ListTypeNode $node) {
return '[' . $node->type . ']';
},
NodeKind::NON_NULL_TYPE => function(NonNullTypeNode $node) {
return $node->type . '!';
},
// Anonymous queries with no directives or variable definitions can use
// the query short form.
return $name === null && strlen($directives ?? '') === 0 && ! $varDefs && $op === 'query'
? $selectionSet
: $this->join([$op, $this->join([$name, $varDefs]), $directives, $selectionSet], ' ');
},
// Type System Definitions
NodeKind::SCHEMA_DEFINITION => function(SchemaDefinitionNode $def) {
return $this->join([
'schema',
$this->join($def->directives, ' '),
$this->block($def->operationTypes)
], ' ');
},
NodeKind::OPERATION_TYPE_DEFINITION => function(OperationTypeDefinitionNode $def) {
return $def->operation . ': ' . $def->type;
},
NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) : string {
return $node->variable
. ': '
. $node->type
. $this->wrap(' = ', $node->defaultValue)
. $this->wrap(' ', $this->join($node->directives, ' '));
},
NodeKind::SCALAR_TYPE_DEFINITION => function(ScalarTypeDefinitionNode $def) {
return $this->join(['scalar', $def->name, $this->join($def->directives, ' ')], ' ');
},
NodeKind::OBJECT_TYPE_DEFINITION => function(ObjectTypeDefinitionNode $def) {
return $this->join([
'type',
$def->name,
$this->wrap('implements ', $this->join($def->interfaces, ', ')),
$this->join($def->directives, ' '),
$this->block($def->fields)
], ' ');
},
NodeKind::FIELD_DEFINITION => function(FieldDefinitionNode $def) {
return $def->name
. $this->wrap('(', $this->join($def->arguments, ', '), ')')
. ': ' . $def->type
. $this->wrap(' ', $this->join($def->directives, ' '));
},
NodeKind::INPUT_VALUE_DEFINITION => function(InputValueDefinitionNode $def) {
return $this->join([
$def->name . ': ' . $def->type,
$this->wrap('= ', $def->defaultValue),
$this->join($def->directives, ' ')
], ' ');
},
NodeKind::INTERFACE_TYPE_DEFINITION => function(InterfaceTypeDefinitionNode $def) {
return $this->join([
'interface',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->fields)
], ' ');
},
NodeKind::UNION_TYPE_DEFINITION => function(UnionTypeDefinitionNode $def) {
return $this->join([
'union',
$def->name,
$this->join($def->directives, ' '),
'= ' . $this->join($def->types, ' | ')
], ' ');
},
NodeKind::ENUM_TYPE_DEFINITION => function(EnumTypeDefinitionNode $def) {
return $this->join([
'enum',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->values)
], ' ');
},
NodeKind::ENUM_VALUE_DEFINITION => function(EnumValueDefinitionNode $def) {
return $this->join([
$def->name,
$this->join($def->directives, ' ')
], ' ');
},
NodeKind::INPUT_OBJECT_TYPE_DEFINITION => function(InputObjectTypeDefinitionNode $def) {
return $this->join([
'input',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->fields)
], ' ');
},
NodeKind::TYPE_EXTENSION_DEFINITION => function(TypeExtensionDefinitionNode $def) {
return "extend {$def->definition}";
},
NodeKind::DIRECTIVE_DEFINITION => function(DirectiveDefinitionNode $def) {
return 'directive @' . $def->name . $this->wrap('(', $this->join($def->arguments, ', '), ')')
. ' on ' . $this->join($def->locations, ' | ');
}
NodeKind::SELECTION_SET => function (SelectionSetNode $node) {
return $this->block($node->selections);
},
NodeKind::FIELD => function (FieldNode $node) : string {
return $this->join(
[
$this->wrap('', $node->alias, ': ') . $node->name . $this->wrap(
'(',
$this->join($node->arguments, ', '),
')'
),
$this->join($node->directives, ' '),
$node->selectionSet,
],
' '
);
},
NodeKind::ARGUMENT => static function (ArgumentNode $node) : string {
return $node->name . ': ' . $node->value;
},
NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) : string {
return '...'
. $node->name
. $this->wrap(' ', $this->join($node->directives, ' '));
},
NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) : string {
return $this->join(
[
'...',
$this->wrap('on ', $node->typeCondition),
$this->join($node->directives, ' '),
$node->selectionSet,
],
' '
);
},
NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) : string {
// Note: fragment variable definitions are experimental and may be changed or removed in the future.
return sprintf('fragment %s', $node->name)
. $this->wrap('(', $this->join($node->variableDefinitions, ', '), ')')
. sprintf(' on %s ', $node->typeCondition)
. $this->wrap('', $this->join($node->directives, ' '), ' ')
. $node->selectionSet;
},
NodeKind::INT => static function (IntValueNode $node) : string {
return $node->value;
},
NodeKind::FLOAT => static function (FloatValueNode $node) : string {
return $node->value;
},
NodeKind::STRING => function (StringValueNode $node, $key) : string {
if ($node->block) {
return $this->printBlockString($node->value, $key === 'description');
}
return json_encode($node->value);
},
NodeKind::BOOLEAN => static function (BooleanValueNode $node) : string {
return $node->value ? 'true' : 'false';
},
NodeKind::NULL => static function (NullValueNode $node) : string {
return 'null';
},
NodeKind::ENUM => static function (EnumValueNode $node) : string {
return $node->value;
},
NodeKind::LST => function (ListValueNode $node) : string {
return '[' . $this->join($node->values, ', ') . ']';
},
NodeKind::OBJECT => function (ObjectValueNode $node) : string {
return '{' . $this->join($node->fields, ', ') . '}';
},
NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) : string {
return $node->name . ': ' . $node->value;
},
NodeKind::DIRECTIVE => function (DirectiveNode $node) : string {
return '@' . $node->name . $this->wrap('(', $this->join($node->arguments, ', '), ')');
},
NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) : string {
// @phpstan-ignore-next-line the printer works bottom up, so this is already a string here
return $node->name;
},
NodeKind::LIST_TYPE => static function (ListTypeNode $node) : string {
return '[' . $node->type . ']';
},
NodeKind::NON_NULL_TYPE => static function (NonNullTypeNode $node) : string {
return $node->type . '!';
},
NodeKind::SCHEMA_DEFINITION => function (SchemaDefinitionNode $def) : string {
return $this->join(
[
'schema',
$this->join($def->directives, ' '),
$this->block($def->operationTypes),
],
' '
);
},
NodeKind::OPERATION_TYPE_DEFINITION => static function (OperationTypeDefinitionNode $def) : string {
return $def->operation . ': ' . $def->type;
},
NodeKind::SCALAR_TYPE_DEFINITION => $this->addDescription(function (ScalarTypeDefinitionNode $def) : string {
return $this->join(['scalar', $def->name, $this->join($def->directives, ' ')], ' ');
}),
NodeKind::OBJECT_TYPE_DEFINITION => $this->addDescription(function (ObjectTypeDefinitionNode $def) : string {
return $this->join(
[
'type',
$def->name,
$this->wrap('implements ', $this->join($def->interfaces, ' & ')),
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
}),
NodeKind::FIELD_DEFINITION => $this->addDescription(function (FieldDefinitionNode $def) : string {
$noIndent = Utils::every($def->arguments, static function (string $arg) : bool {
return strpos($arg, "\n") === false;
});
return $def->name
. ($noIndent
? $this->wrap('(', $this->join($def->arguments, ', '), ')')
: $this->wrap("(\n", $this->indent($this->join($def->arguments, "\n")), "\n)"))
. ': ' . $def->type
. $this->wrap(' ', $this->join($def->directives, ' '));
}),
NodeKind::INPUT_VALUE_DEFINITION => $this->addDescription(function (InputValueDefinitionNode $def) : string {
return $this->join(
[
$def->name . ': ' . $def->type,
$this->wrap('= ', $def->defaultValue),
$this->join($def->directives, ' '),
],
' '
);
}),
NodeKind::INTERFACE_TYPE_DEFINITION => $this->addDescription(
function (InterfaceTypeDefinitionNode $def) : string {
return $this->join(
[
'interface',
$def->name,
$this->wrap('implements ', $this->join($def->interfaces, ' & ')),
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
}
),
NodeKind::UNION_TYPE_DEFINITION => $this->addDescription(function (UnionTypeDefinitionNode $def) : string {
return $this->join(
[
'union',
$def->name,
$this->join($def->directives, ' '),
count($def->types ?? []) > 0
? '= ' . $this->join($def->types, ' | ')
: '',
],
' '
);
}),
NodeKind::ENUM_TYPE_DEFINITION => $this->addDescription(function (EnumTypeDefinitionNode $def) : string {
return $this->join(
[
'enum',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->values),
],
' '
);
}),
NodeKind::ENUM_VALUE_DEFINITION => $this->addDescription(function (EnumValueDefinitionNode $def) : string {
return $this->join([$def->name, $this->join($def->directives, ' ')], ' ');
}),
NodeKind::INPUT_OBJECT_TYPE_DEFINITION => $this->addDescription(function (
InputObjectTypeDefinitionNode $def
) : string {
return $this->join(
[
'input',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
}),
NodeKind::SCHEMA_EXTENSION => function (SchemaTypeExtensionNode $def) : string {
return $this->join(
[
'extend schema',
$this->join($def->directives, ' '),
$this->block($def->operationTypes),
],
' '
);
},
NodeKind::SCALAR_TYPE_EXTENSION => function (ScalarTypeExtensionNode $def) : string {
return $this->join(
[
'extend scalar',
$def->name,
$this->join($def->directives, ' '),
],
' '
);
},
NodeKind::OBJECT_TYPE_EXTENSION => function (ObjectTypeExtensionNode $def) : string {
return $this->join(
[
'extend type',
$def->name,
$this->wrap('implements ', $this->join($def->interfaces, ' & ')),
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
},
NodeKind::INTERFACE_TYPE_EXTENSION => function (InterfaceTypeExtensionNode $def) : string {
return $this->join(
[
'extend interface',
$def->name,
$this->wrap('implements ', $this->join($def->interfaces, ' & ')),
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
},
NodeKind::UNION_TYPE_EXTENSION => function (UnionTypeExtensionNode $def) : string {
return $this->join(
[
'extend union',
$def->name,
$this->join($def->directives, ' '),
count($def->types ?? []) > 0
? '= ' . $this->join($def->types, ' | ')
: '',
],
' '
);
},
NodeKind::ENUM_TYPE_EXTENSION => function (EnumTypeExtensionNode $def) : string {
return $this->join(
[
'extend enum',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->values),
],
' '
);
},
NodeKind::INPUT_OBJECT_TYPE_EXTENSION => function (InputObjectTypeExtensionNode $def) : string {
return $this->join(
[
'extend input',
$def->name,
$this->join($def->directives, ' '),
$this->block($def->fields),
],
' '
);
},
NodeKind::DIRECTIVE_DEFINITION => $this->addDescription(function (DirectiveDefinitionNode $def) : string {
$noIndent = Utils::every($def->arguments, static function (string $arg) : bool {
return strpos($arg, "\n") === false;
});
return 'directive @'
. $def->name
. ($noIndent
? $this->wrap('(', $this->join($def->arguments, ', '), ')')
: $this->wrap("(\n", $this->indent($this->join($def->arguments, "\n")), "\n"))
. ($def->repeatable ? ' repeatable' : '')
. ' on ' . $this->join($def->locations, ' | ');
}),
],
]
]);
);
}
public function addDescription(callable $cb)
{
return function ($node) use ($cb) : string {
return $this->join([$node->description, $cb($node)], "\n");
};
}
/**
@@ -277,12 +488,14 @@ class Printer
*/
public function block($array)
{
return $array && $this->length($array) ? $this->indent("{\n" . $this->join($array, "\n")) . "\n}" : '{}';
return $array && $this->length($array)
? "{\n" . $this->indent($this->join($array, "\n")) . "\n}"
: '';
}
public function indent($maybeString)
{
return $maybeString ? str_replace("\n", "\n ", $maybeString) : '';
return $maybeString ? ' ' . str_replace("\n", "\n ", $maybeString) : '';
}
public function manyList($start, $list, $separator, $end)
@@ -295,16 +508,32 @@ class Printer
return $maybeArray ? count($maybeArray) : 0;
}
public function join($maybeArray, $separator = '')
public function join($maybeArray, $separator = '') : string
{
return $maybeArray
? implode(
$separator,
Utils::filter(
$maybeArray,
function($x) { return !!$x;}
static function ($x) : bool {
return (bool) $x;
}
)
)
: '';
}
/**
* Print a block string in the indented block form by adding a leading and
* trailing blank line. However, if a block string starts with whitespace and is
* a single-line, adding a leading blank line would strip that whitespace.
*/
private function printBlockString($value, $isDescription)
{
$escaped = str_replace('"""', '\\"""', $value);
return ($value[0] === ' ' || $value[0] === "\t") && strpos($value, "\n") === false
? ('"""' . preg_replace('/"$/', "\"\n", $escaped) . '"""')
: ('"""' . "\n" . ($isDescription ? $escaped : $this->indent($escaped)) . "\n" . '"""');
}
}
+27 -31
View File
@@ -1,37 +1,32 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
use GraphQL\Utils\Utils;
use function is_string;
use function json_decode;
use function mb_strlen;
use function mb_substr;
use function preg_match_all;
use const PREG_OFFSET_CAPTURE;
/**
* Class Source
* @package GraphQL\Language
*/
class Source
{
/**
* @var string
*/
/** @var string */
public $body;
/**
* @var int
*/
/** @var int */
public $length;
/**
* @var string
*/
/** @var string */
public $name;
/**
* @var SourceLocation
*/
/** @var SourceLocation */
public $locationOffset;
/**
* Source constructor.
*
* A representation of source input to GraphQL.
* `name` and `locationOffset` are optional. They are useful for clients who
* store GraphQL documents in source files; for example, if the GraphQL input
@@ -39,21 +34,20 @@ class Source
* be "Foo.graphql" and location to be `{ line: 40, column: 0 }`.
* line and column in locationOffset are 1-indexed
*
* @param $body
* @param null $name
* @param SourceLocation|null $location
* @param string $body
* @param string|null $name
*/
public function __construct($body, $name = null, SourceLocation $location = null)
public function __construct($body, $name = null, ?SourceLocation $location = null)
{
Utils::invariant(
is_string($body),
'GraphQL query body is expected to be string, but got ' . Utils::getVariableType($body)
);
$this->body = $body;
$this->length = mb_strlen($body, 'UTF-8');
$this->name = $name ?: 'GraphQL';
$this->locationOffset = $location ?: new SourceLocation(1, 1);
$this->body = $body;
$this->length = mb_strlen($body, 'UTF-8');
$this->name = $name === '' || $name === null ? 'GraphQL request' : $name;
$this->locationOffset = $location ?? new SourceLocation(1, 1);
Utils::invariant(
$this->locationOffset->line > 0,
@@ -66,21 +60,23 @@ class Source
}
/**
* @param $position
* @param int $position
*
* @return SourceLocation
*/
public function getLocation($position)
{
$line = 1;
$line = 1;
$column = $position + 1;
$utfChars = json_decode('"\u2028\u2029"');
$lineRegexp = '/\r\n|[\n\r'.$utfChars.']/su';
$matches = [];
$utfChars = json_decode('"\u2028\u2029"');
$lineRegexp = '/\r\n|[\n\r' . $utfChars . ']/su';
$matches = [];
preg_match_all($lineRegexp, mb_substr($this->body, 0, $position, 'UTF-8'), $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $index => $match) {
$line += 1;
$column = $position + 1 - ($match[1] + mb_strlen($match[0], 'UTF-8'));
}
+20 -12
View File
@@ -1,30 +1,42 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
class SourceLocation implements \JsonSerializable
use JsonSerializable;
class SourceLocation implements JsonSerializable
{
/** @var int */
public $line;
/** @var int */
public $column;
/**
* @param int $line
* @param int $col
*/
public function __construct($line, $col)
{
$this->line = $line;
$this->line = $line;
$this->column = $col;
}
/**
* @return array
* @return int[]
*/
public function toArray()
{
return [
'line' => $this->line,
'column' => $this->column
'line' => $this->line,
'column' => $this->column,
];
}
/**
* @return array
* @return int[]
*/
public function toSerializableArray()
{
@@ -32,13 +44,9 @@ class SourceLocation implements \JsonSerializable
}
/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
* @return int[]
*/
function jsonSerialize()
public function jsonSerialize()
{
return $this->toSerializableArray();
}
+48 -90
View File
@@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
/**
@@ -8,59 +11,28 @@ namespace GraphQL\Language;
class Token
{
// Each kind of token.
const SOF = '<SOF>';
const EOF = '<EOF>';
const BANG = '!';
const DOLLAR = '$';
const PAREN_L = '(';
const PAREN_R = ')';
const SPREAD = '...';
const COLON = ':';
const EQUALS = '=';
const AT = '@';
const BRACKET_L = '[';
const BRACKET_R = ']';
const BRACE_L = '{';
const PIPE = '|';
const BRACE_R = '}';
const NAME = 'Name';
const INT = 'Int';
const FLOAT = 'Float';
const STRING = 'String';
const COMMENT = 'Comment';
/**
* @param $kind
* @return mixed
*/
public static function getKindDescription($kind)
{
trigger_error('Deprecated as of 16.10.2016 ($kind itself contains description string now)', E_USER_DEPRECATED);
$description = [];
$description[self::SOF] = '<SOF>';
$description[self::EOF] = '<EOF>';
$description[self::BANG] = '!';
$description[self::DOLLAR] = '$';
$description[self::PAREN_L] = '(';
$description[self::PAREN_R] = ')';
$description[self::SPREAD] = '...';
$description[self::COLON] = ':';
$description[self::EQUALS] = '=';
$description[self::AT] = '@';
$description[self::BRACKET_L] = '[';
$description[self::BRACKET_R] = ']';
$description[self::BRACE_L] = '{';
$description[self::PIPE] = '|';
$description[self::BRACE_R] = '}';
$description[self::NAME] = 'Name';
$description[self::INT] = 'Int';
$description[self::FLOAT] = 'Float';
$description[self::STRING] = 'String';
$description[self::COMMENT] = 'Comment';
return $description[$kind];
}
public const SOF = '<SOF>';
public const EOF = '<EOF>';
public const BANG = '!';
public const DOLLAR = '$';
public const AMP = '&';
public const PAREN_L = '(';
public const PAREN_R = ')';
public const SPREAD = '...';
public const COLON = ':';
public const EQUALS = '=';
public const AT = '@';
public const BRACKET_L = '[';
public const BRACKET_R = ']';
public const BRACE_L = '{';
public const PIPE = '|';
public const BRACE_R = '}';
public const NAME = 'Name';
public const INT = 'Int';
public const FLOAT = 'Float';
public const STRING = 'String';
public const BLOCK_STRING = 'BlockString';
public const COMMENT = 'Comment';
/**
* The kind of Token (see one of constants above).
@@ -97,9 +69,7 @@ class Token
*/
public $column;
/**
* @var string|null
*/
/** @var string|null */
public $value;
/**
@@ -111,51 +81,39 @@ class Token
*/
public $prev;
/**
* @var Token
*/
/** @var Token|null */
public $next;
/**
* Token constructor.
* @param $kind
* @param $start
* @param $end
* @param $line
* @param $column
* @param Token $previous
* @param null $value
* @param mixed $value
*/
public function __construct($kind, $start, $end, $line, $column, Token $previous = null, $value = null)
public function __construct(string $kind, int $start, int $end, int $line, int $column, ?Token $previous = null, $value = null)
{
$this->kind = $kind;
$this->start = (int) $start;
$this->end = (int) $end;
$this->line = (int) $line;
$this->column = (int) $column;
$this->prev = $previous;
$this->next = null;
$this->value = $value;
$this->kind = $kind;
$this->start = $start;
$this->end = $end;
$this->line = $line;
$this->column = $column;
$this->prev = $previous;
$this->next = null;
$this->value = $value;
}
public function getDescription() : string
{
return $this->kind . ($this->value === null ? '' : ' "' . $this->value . '"');
}
/**
* @return string
* @return (string|int|null)[]
*/
public function getDescription()
{
return $this->kind . ($this->value ? ' "' . $this->value . '"' : '');
}
/**
* @return array
*/
public function toArray()
public function toArray() : array
{
return [
'kind' => $this->kind,
'value' => $this->value,
'line' => $this->line,
'column' => $this->column
'kind' => $this->kind,
'value' => $this->value,
'line' => $this->line,
'column' => $this->column,
];
}
}
+217 -165
View File
@@ -1,19 +1,24 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
use ArrayObject;
use Exception;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\AST\NodeList;
use GraphQL\Utils\TypeInfo;
class VisitorOperation
{
public $doBreak;
public $doContinue;
public $removeNode;
}
use SplFixedArray;
use stdClass;
use function array_pop;
use function array_splice;
use function count;
use function func_get_args;
use function is_array;
use function is_callable;
use function json_encode;
/**
* Utility for efficient AST traversal and modification.
@@ -104,84 +109,105 @@ class VisitorOperation
*/
class Visitor
{
/** @var string[][] */
public static $visitorKeys = [
NodeKind::NAME => [],
NodeKind::DOCUMENT => ['definitions'],
NodeKind::NAME => [],
NodeKind::DOCUMENT => ['definitions'],
NodeKind::OPERATION_DEFINITION => ['name', 'variableDefinitions', 'directives', 'selectionSet'],
NodeKind::VARIABLE_DEFINITION => ['variable', 'type', 'defaultValue'],
NodeKind::VARIABLE => ['name'],
NodeKind::SELECTION_SET => ['selections'],
NodeKind::FIELD => ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
NodeKind::ARGUMENT => ['name', 'value'],
NodeKind::FRAGMENT_SPREAD => ['name', 'directives'],
NodeKind::INLINE_FRAGMENT => ['typeCondition', 'directives', 'selectionSet'],
NodeKind::FRAGMENT_DEFINITION => ['name', 'typeCondition', 'directives', 'selectionSet'],
NodeKind::VARIABLE_DEFINITION => ['variable', 'type', 'defaultValue', 'directives'],
NodeKind::VARIABLE => ['name'],
NodeKind::SELECTION_SET => ['selections'],
NodeKind::FIELD => ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
NodeKind::ARGUMENT => ['name', 'value'],
NodeKind::FRAGMENT_SPREAD => ['name', 'directives'],
NodeKind::INLINE_FRAGMENT => ['typeCondition', 'directives', 'selectionSet'],
NodeKind::FRAGMENT_DEFINITION => [
'name',
// Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
'variableDefinitions',
'typeCondition',
'directives',
'selectionSet',
],
NodeKind::INT => [],
NodeKind::FLOAT => [],
NodeKind::STRING => [],
NodeKind::BOOLEAN => [],
NodeKind::NULL => [],
NodeKind::ENUM => [],
NodeKind::LST => ['values'],
NodeKind::OBJECT => ['fields'],
NodeKind::OBJECT_FIELD => ['name', 'value'],
NodeKind::DIRECTIVE => ['name', 'arguments'],
NodeKind::NAMED_TYPE => ['name'],
NodeKind::LIST_TYPE => ['type'],
NodeKind::INT => [],
NodeKind::FLOAT => [],
NodeKind::STRING => [],
NodeKind::BOOLEAN => [],
NodeKind::NULL => [],
NodeKind::ENUM => [],
NodeKind::LST => ['values'],
NodeKind::OBJECT => ['fields'],
NodeKind::OBJECT_FIELD => ['name', 'value'],
NodeKind::DIRECTIVE => ['name', 'arguments'],
NodeKind::NAMED_TYPE => ['name'],
NodeKind::LIST_TYPE => ['type'],
NodeKind::NON_NULL_TYPE => ['type'],
NodeKind::SCHEMA_DEFINITION => ['directives', 'operationTypes'],
NodeKind::OPERATION_TYPE_DEFINITION => ['type'],
NodeKind::SCALAR_TYPE_DEFINITION => ['name', 'directives'],
NodeKind::OBJECT_TYPE_DEFINITION => ['name', 'interfaces', 'directives', 'fields'],
NodeKind::FIELD_DEFINITION => ['name', 'arguments', 'type', 'directives'],
NodeKind::INPUT_VALUE_DEFINITION => ['name', 'type', 'defaultValue', 'directives'],
NodeKind::INTERFACE_TYPE_DEFINITION => [ 'name', 'directives', 'fields' ],
NodeKind::UNION_TYPE_DEFINITION => [ 'name', 'directives', 'types' ],
NodeKind::ENUM_TYPE_DEFINITION => [ 'name', 'directives', 'values' ],
NodeKind::ENUM_VALUE_DEFINITION => [ 'name', 'directives' ],
NodeKind::INPUT_OBJECT_TYPE_DEFINITION => [ 'name', 'directives', 'fields' ],
NodeKind::TYPE_EXTENSION_DEFINITION => [ 'definition' ],
NodeKind::DIRECTIVE_DEFINITION => [ 'name', 'arguments', 'locations' ]
NodeKind::SCHEMA_DEFINITION => ['directives', 'operationTypes'],
NodeKind::OPERATION_TYPE_DEFINITION => ['type'],
NodeKind::SCALAR_TYPE_DEFINITION => ['description', 'name', 'directives'],
NodeKind::OBJECT_TYPE_DEFINITION => ['description', 'name', 'interfaces', 'directives', 'fields'],
NodeKind::FIELD_DEFINITION => ['description', 'name', 'arguments', 'type', 'directives'],
NodeKind::INPUT_VALUE_DEFINITION => ['description', 'name', 'type', 'defaultValue', 'directives'],
NodeKind::INTERFACE_TYPE_DEFINITION => ['description', 'name', 'interfaces', 'directives', 'fields'],
NodeKind::UNION_TYPE_DEFINITION => ['description', 'name', 'directives', 'types'],
NodeKind::ENUM_TYPE_DEFINITION => ['description', 'name', 'directives', 'values'],
NodeKind::ENUM_VALUE_DEFINITION => ['description', 'name', 'directives'],
NodeKind::INPUT_OBJECT_TYPE_DEFINITION => ['description', 'name', 'directives', 'fields'],
NodeKind::SCALAR_TYPE_EXTENSION => ['name', 'directives'],
NodeKind::OBJECT_TYPE_EXTENSION => ['name', 'interfaces', 'directives', 'fields'],
NodeKind::INTERFACE_TYPE_EXTENSION => ['name', 'interfaces', 'directives', 'fields'],
NodeKind::UNION_TYPE_EXTENSION => ['name', 'directives', 'types'],
NodeKind::ENUM_TYPE_EXTENSION => ['name', 'directives', 'values'],
NodeKind::INPUT_OBJECT_TYPE_EXTENSION => ['name', 'directives', 'fields'],
NodeKind::DIRECTIVE_DEFINITION => ['description', 'name', 'arguments', 'locations'],
NodeKind::SCHEMA_EXTENSION => ['directives', 'operationTypes'],
];
/**
* Visit the AST (see class description for details)
*
* @api
* @param Node $root
* @param array $visitor
* @param array $keyMap
* @param Node|ArrayObject|stdClass $root
* @param callable[] $visitor
* @param mixed[]|null $keyMap
*
* @return Node|mixed
* @throws \Exception
*
* @throws Exception
*
* @api
*/
public static function visit($root, $visitor, $keyMap = null)
{
$visitorKeys = $keyMap ?: self::$visitorKeys;
$visitorKeys = $keyMap ?? self::$visitorKeys;
$stack = null;
$inArray = $root instanceof NodeList || is_array($root);
$keys = [$root];
$index = -1;
$edits = [];
$parent = null;
$path = [];
$stack = null;
$inArray = $root instanceof NodeList || is_array($root);
$keys = [$root];
$index = -1;
$edits = [];
$parent = null;
$path = [];
$ancestors = [];
$newRoot = $root;
$newRoot = $root;
$UNDEFINED = null;
do {
$index++;
$isLeaving = $index === count($keys);
$key = null;
$node = null;
$isEdited = $isLeaving && count($edits) !== 0;
$key = null;
$node = null;
$isEdited = $isLeaving && count($edits) > 0;
if ($isLeaving) {
$key = count($ancestors) === 0 ? $UNDEFINED : array_pop($path);
$node = $parent;
$key = ! $ancestors ? $UNDEFINED : $path[count($path) - 1];
$node = $parent;
$parent = array_pop($ancestors);
if ($isEdited) {
@@ -195,18 +221,14 @@ class Visitor
}
$editOffset = 0;
for ($ii = 0; $ii < count($edits); $ii++) {
$editKey = $edits[$ii][0];
$editKey = $edits[$ii][0];
$editValue = $edits[$ii][1];
if ($inArray) {
$editKey -= $editOffset;
}
if ($inArray && $editValue === null) {
if ($node instanceof NodeList) {
$node->splice($editKey, 1);
} else {
array_splice($node, $editKey, 1);
}
$node->splice($editKey, 1);
$editOffset++;
} else {
if ($node instanceof NodeList || is_array($node)) {
@@ -217,39 +239,50 @@ class Visitor
}
}
}
$index = $stack['index'];
$keys = $stack['keys'];
$edits = $stack['edits'];
$index = $stack['index'];
$keys = $stack['keys'];
$edits = $stack['edits'];
$inArray = $stack['inArray'];
$stack = $stack['prev'];
$stack = $stack['prev'];
} else {
$key = $parent ? ($inArray ? $index : $keys[$index]) : $UNDEFINED;
$node = $parent ? (($parent instanceof NodeList || is_array($parent)) ? $parent[$key] : $parent->{$key}) : $newRoot;
$key = $parent !== null
? ($inArray
? $index
: $keys[$index]
)
: $UNDEFINED;
$node = $parent !== null
? ($parent instanceof NodeList || is_array($parent)
? $parent[$key]
: $parent->{$key}
)
: $newRoot;
if ($node === null || $node === $UNDEFINED) {
continue;
}
if ($parent) {
if ($parent !== null) {
$path[] = $key;
}
}
$result = null;
if (!$node instanceof NodeList && !is_array($node)) {
if (!($node instanceof Node)) {
throw new \Exception('Invalid AST Node: ' . json_encode($node));
if (! $node instanceof NodeList && ! is_array($node)) {
if (! ($node instanceof Node)) {
throw new Exception('Invalid AST Node: ' . json_encode($node));
}
$visitFn = self::getVisitFn($visitor, $node->kind, $isLeaving);
if ($visitFn) {
$result = call_user_func($visitFn, $node, $key, $parent, $path, $ancestors);
if ($visitFn !== null) {
$result = $visitFn($node, $key, $parent, $path, $ancestors);
$editValue = null;
if ($result !== null) {
if ($result instanceof VisitorOperation) {
if ($result->doBreak) {
break;
}
if (!$isLeaving && $result->doContinue) {
if (! $isLeaving && $result->doContinue) {
array_pop($path);
continue;
}
@@ -261,13 +294,13 @@ class Visitor
}
$edits[] = [$key, $editValue];
if (!$isLeaving) {
if ($editValue instanceof Node) {
$node = $editValue;
} else {
if (! $isLeaving) {
if (! ($editValue instanceof Node)) {
array_pop($path);
continue;
}
$node = $editValue;
}
}
}
@@ -277,28 +310,29 @@ class Visitor
$edits[] = [$key, $node];
}
if (!$isLeaving) {
$stack = [
if ($isLeaving) {
array_pop($path);
} else {
$stack = [
'inArray' => $inArray,
'index' => $index,
'keys' => $keys,
'edits' => $edits,
'prev' => $stack
'index' => $index,
'keys' => $keys,
'edits' => $edits,
'prev' => $stack,
];
$inArray = $node instanceof NodeList || is_array($node);
$keys = ($inArray ? $node : $visitorKeys[$node->kind]) ?: [];
$keys = ($inArray ? $node : $visitorKeys[$node->kind]) ?? [];
$index = -1;
$edits = [];
if ($parent) {
if ($parent !== null) {
$ancestors[] = $parent;
}
$parent = $node;
}
} while ($stack);
if (count($edits) !== 0) {
if (count($edits) > 0) {
$newRoot = $edits[0][1];
}
@@ -308,97 +342,116 @@ class Visitor
/**
* Returns marker for visitor break
*
* @api
* @return VisitorOperation
*
* @api
*/
public static function stop()
{
$r = new VisitorOperation();
$r = new VisitorOperation();
$r->doBreak = true;
return $r;
}
/**
* Returns marker for skipping current node
*
* @api
* @return VisitorOperation
*
* @api
*/
public static function skipNode()
{
$r = new VisitorOperation();
$r = new VisitorOperation();
$r->doContinue = true;
return $r;
}
/**
* Returns marker for removing a node
*
* @api
* @return VisitorOperation
*
* @api
*/
public static function removeNode()
{
$r = new VisitorOperation();
$r = new VisitorOperation();
$r->removeNode = true;
return $r;
}
/**
* @param $visitors
* @return array
* @param callable[][] $visitors
*
* @return array<string, callable>
*/
static function visitInParallel($visitors)
public static function visitInParallel($visitors)
{
$visitorsCount = count($visitors);
$skipping = new \SplFixedArray($visitorsCount);
$skipping = new SplFixedArray($visitorsCount);
return [
'enter' => function ($node) use ($visitors, $skipping, $visitorsCount) {
'enter' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) {
for ($i = 0; $i < $visitorsCount; $i++) {
if (empty($skipping[$i])) {
$fn = self::getVisitFn($visitors[$i], $node->kind, /* isLeaving */ false);
if ($skipping[$i] !== null) {
continue;
}
if ($fn) {
$result = call_user_func_array($fn, func_get_args());
$fn = self::getVisitFn(
$visitors[$i],
$node->kind, /* isLeaving */
false
);
if ($result instanceof VisitorOperation) {
if ($result->doContinue) {
$skipping[$i] = $node;
} else if ($result->doBreak) {
$skipping[$i] = $result;
} else if ($result->removeNode) {
return $result;
}
} else if ($result !== null) {
return $result;
}
if (! $fn) {
continue;
}
$result = $fn(...func_get_args());
if ($result instanceof VisitorOperation) {
if ($result->doContinue) {
$skipping[$i] = $node;
} elseif ($result->doBreak) {
$skipping[$i] = $result;
} elseif ($result->removeNode) {
return $result;
}
} elseif ($result !== null) {
return $result;
}
}
},
'leave' => function ($node) use ($visitors, $skipping, $visitorsCount) {
'leave' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) {
for ($i = 0; $i < $visitorsCount; $i++) {
if (empty($skipping[$i])) {
$fn = self::getVisitFn($visitors[$i], $node->kind, /* isLeaving */ true);
if ($skipping[$i] === null) {
$fn = self::getVisitFn(
$visitors[$i],
$node->kind, /* isLeaving */
true
);
if ($fn) {
$result = call_user_func_array($fn, func_get_args());
if (isset($fn)) {
$result = $fn(...func_get_args());
if ($result instanceof VisitorOperation) {
if ($result->doBreak) {
$skipping[$i] = $result;
} else if ($result->removeNode) {
} elseif ($result->removeNode) {
return $result;
}
} else if ($result !== null) {
} elseif ($result !== null) {
return $result;
}
}
} else if ($skipping[$i] === $node) {
} elseif ($skipping[$i] === $node) {
$skipping[$i] = null;
}
}
}
},
];
}
@@ -406,81 +459,80 @@ class Visitor
* Creates a new visitor instance which maintains a provided TypeInfo instance
* along with visiting visitor.
*/
static function visitWithTypeInfo(TypeInfo $typeInfo, $visitor)
public static function visitWithTypeInfo(TypeInfo $typeInfo, $visitor)
{
return [
'enter' => function ($node) use ($typeInfo, $visitor) {
'enter' => static function (Node $node) use ($typeInfo, $visitor) {
$typeInfo->enter($node);
$fn = self::getVisitFn($visitor, $node->kind, false);
if ($fn) {
$result = call_user_func_array($fn, func_get_args());
if ($result) {
if (isset($fn)) {
$result = $fn(...func_get_args());
if ($result !== null) {
$typeInfo->leave($node);
if ($result instanceof Node) {
$typeInfo->enter($result);
}
}
return $result;
}
return null;
},
'leave' => function ($node) use ($typeInfo, $visitor) {
$fn = self::getVisitFn($visitor, $node->kind, true);
$result = $fn ? call_user_func_array($fn, func_get_args()) : null;
'leave' => static function (Node $node) use ($typeInfo, $visitor) {
$fn = self::getVisitFn($visitor, $node->kind, true);
$result = $fn !== null
? $fn(...func_get_args())
: null;
$typeInfo->leave($node);
return $result;
}
},
];
}
/**
* @param $visitor
* @param $kind
* @param $isLeaving
* @return null
* @param callable[]|null $visitor
* @param string $kind
* @param bool $isLeaving
*/
public static function getVisitFn($visitor, $kind, $isLeaving)
public static function getVisitFn($visitor, $kind, $isLeaving) : ?callable
{
if (!$visitor) {
if ($visitor === null) {
return null;
}
$kindVisitor = isset($visitor[$kind]) ? $visitor[$kind] : null;
if (!$isLeaving && is_callable($kindVisitor)) {
// { Kind() {} }
return $kindVisitor;
}
$kindVisitor = $visitor[$kind] ?? null;
if (is_array($kindVisitor)) {
if ($isLeaving) {
$kindSpecificVisitor = isset($kindVisitor['leave']) ? $kindVisitor['leave'] : null;
$kindSpecificVisitor = $kindVisitor['leave'] ?? null;
} else {
$kindSpecificVisitor = isset($kindVisitor['enter']) ? $kindVisitor['enter'] : null;
$kindSpecificVisitor = $kindVisitor['enter'] ?? null;
}
if ($kindSpecificVisitor && is_callable($kindSpecificVisitor)) {
// { Kind: { enter() {}, leave() {} } }
return $kindSpecificVisitor;
}
return null;
return $kindSpecificVisitor;
}
if ($kindVisitor !== null && ! $isLeaving) {
return $kindVisitor;
}
$visitor += ['leave' => null, 'enter' => null];
$specificVisitor = $isLeaving ? $visitor['leave'] : $visitor['enter'];
if ($specificVisitor) {
if (is_callable($specificVisitor)) {
if (isset($specificVisitor)) {
if (! is_array($specificVisitor)) {
// { enter() {}, leave() {} }
return $specificVisitor;
}
$specificKindVisitor = isset($specificVisitor[$kind]) ? $specificVisitor[$kind] : null;
if (is_callable($specificKindVisitor)) {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return $specificKindVisitor;
}
return $specificVisitor[$kind] ?? null;
}
return null;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace GraphQL\Language;
class VisitorOperation
{
/** @var bool */
public $doBreak;
/** @var bool */
public $doContinue;
/** @var bool */
public $removeNode;
}
-12
View File
@@ -1,12 +0,0 @@
<?php
namespace GraphQL;
/**
* Schema Definition
*
* @deprecated moved to GraphQL\Type\Schema
*/
class Schema extends \GraphQL\Type\Schema
{
}
-603
View File
@@ -1,603 +0,0 @@
<?php
namespace GraphQL;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\Executor;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\Parser;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Resolution;
use GraphQL\Validator\DocumentValidator;
use GraphQL\Utils\Utils;
trigger_error(
'GraphQL\Server is deprecated in favor of new implementation: GraphQL\Server\StandardServer and will be removed in next version',
E_USER_DEPRECATED
);
class Server
{
const DEBUG_PHP_ERRORS = 1;
const DEBUG_EXCEPTIONS = 2;
const DEBUG_ALL = 7;
private $queryType;
private $mutationType;
private $subscriptionType;
private $directives;
private $types = [];
private $schema;
private $debug = 0;
private $contextValue;
private $rootValue;
/**
* @var callable
*/
private $phpErrorFormatter = ['GraphQL\Error\FormattedError', 'createFromPHPError'];
/**
* @var callable
*/
private $exceptionFormatter = ['GraphQL\Error\FormattedError', 'createFromException'];
private $unexpectedErrorMessage = 'Unexpected Error';
private $unexpectedErrorStatus = 500;
private $validationRules;
/**
* @var Resolution
*/
private $typeResolutionStrategy;
/**
* @var PromiseAdapter
*/
private $promiseAdapter;
private $phpErrors = [];
/**
* @return static
*/
public static function create()
{
return new static();
}
/**
* @return ObjectType|null
*/
public function getQueryType()
{
return $this->queryType;
}
/**
* @param ObjectType $queryType
* @return Server
*/
public function setQueryType(ObjectType $queryType)
{
$this->assertSchemaNotSet('Query Type', __METHOD__);
$this->queryType = $queryType;
return $this;
}
/**
* @return ObjectType|null
*/
public function getMutationType()
{
return $this->mutationType;
}
/**
* @param ObjectType $mutationType
* @return Server
*/
public function setMutationType(ObjectType $mutationType)
{
$this->assertSchemaNotSet('Mutation Type', __METHOD__);
$this->mutationType = $mutationType;
return $this;
}
/**
* @return ObjectType|null
*/
public function getSubscriptionType()
{
return $this->subscriptionType;
}
/**
* @param ObjectType $subscriptionType
* @return Server
*/
public function setSubscriptionType($subscriptionType)
{
$this->assertSchemaNotSet('Subscription Type', __METHOD__);
$this->subscriptionType = $subscriptionType;
return $this;
}
/**
* @param Type[] $types
* @return Server
*/
public function addTypes(array $types)
{
if (!empty($types)) {
$this->assertSchemaNotSet('Types', __METHOD__);
$this->types = array_merge($this->types, $types);
}
return $this;
}
/**
* @return array
*/
public function getTypes()
{
return $this->types;
}
/**
* @return Directive[]
*/
public function getDirectives()
{
if (null === $this->directives) {
$this->directives = Directive::getInternalDirectives();
}
return $this->directives;
}
/**
* @param Directive[] $directives
* @return Server
*/
public function setDirectives(array $directives)
{
$this->assertSchemaNotSet('Directives', __METHOD__);
$this->directives = $directives;
return $this;
}
/**
* @return int
*/
public function getDebug()
{
return $this->debug;
}
/**
* @param int $debug
* @return Server
*/
public function setDebug($debug = self::DEBUG_ALL)
{
$this->debug = (int) $debug;
return $this;
}
/**
* @return mixed
*/
public function getContext()
{
return $this->contextValue;
}
/**
* @param mixed $context
* @return Server
*/
public function setContext($context)
{
$this->contextValue = $context;
return $this;
}
/**
* @param $rootValue
* @return Server
*/
public function setRootValue($rootValue)
{
$this->rootValue = $rootValue;
return $this;
}
/**
* @return mixed
*/
public function getRootValue()
{
return $this->rootValue;
}
/**
* Set schema instance manually. Mutually exclusive with `setQueryType`, `setMutationType`, `setSubscriptionType`, `setDirectives`, `addTypes`
*
* @param Schema $schema
* @return $this
*/
public function setSchema(Schema $schema)
{
if ($this->queryType) {
$err = 'Query Type is already set';
$errMethod = __CLASS__ . '::setQueryType';
} else if ($this->mutationType) {
$err = 'Mutation Type is already set';
$errMethod = __CLASS__ . '::setMutationType';
} else if ($this->subscriptionType) {
$err = 'Subscription Type is already set';
$errMethod = __CLASS__ . '::setSubscriptionType';
} else if ($this->directives) {
$err = 'Directives are already set';
$errMethod = __CLASS__ . '::setDirectives';
} else if ($this->types) {
$err = 'Additional types are already set';
$errMethod = __CLASS__ . '::addTypes';
} else if ($this->typeResolutionStrategy) {
$err = 'Type Resolution Strategy is already set';
$errMethod = __CLASS__ . '::setTypeResolutionStrategy';
} else if ($this->schema && $this->schema !== $schema) {
$err = 'Different schema is already set';
}
if (isset($err)) {
if (isset($errMethod)) {
$err .= " ($errMethod is mutually exclusive with " . __METHOD__ . ")";
}
throw new InvariantViolation("Cannot set Schema on Server: $err");
}
$this->schema = $schema;
return $this;
}
/**
* @param $entry
* @param $mutuallyExclusiveMethod
*/
private function assertSchemaNotSet($entry, $mutuallyExclusiveMethod)
{
if ($this->schema) {
$schemaMethod = __CLASS__ . '::setSchema';
throw new InvariantViolation("Cannot set $entry on Server: Schema is already set ($mutuallyExclusiveMethod is mutually exclusive with $schemaMethod)");
}
}
/**
* @return Schema
*/
public function getSchema()
{
if (null === $this->schema) {
$this->schema = new Schema([
'query' => $this->queryType,
'mutation' => $this->mutationType,
'subscription' => $this->subscriptionType,
'directives' => $this->directives,
'types' => $this->types,
'typeResolution' => $this->typeResolutionStrategy
]);
}
return $this->schema;
}
/**
* @return callable
*/
public function getPhpErrorFormatter()
{
return $this->phpErrorFormatter;
}
/**
* Expects function(\ErrorException $e) : array
*
* @param callable $phpErrorFormatter
* @return $this
*/
public function setPhpErrorFormatter(callable $phpErrorFormatter)
{
$this->phpErrorFormatter = $phpErrorFormatter;
return $this;
}
/**
* @return callable
*/
public function getExceptionFormatter()
{
return $this->exceptionFormatter;
}
/**
* Expects function(Exception $e) : array
*
* @param callable $exceptionFormatter
* @return $this
*/
public function setExceptionFormatter(callable $exceptionFormatter)
{
$this->exceptionFormatter = $exceptionFormatter;
return $this;
}
/**
* @return string
*/
public function getUnexpectedErrorMessage()
{
return $this->unexpectedErrorMessage;
}
/**
* @param string $unexpectedErrorMessage
* @return $this
*/
public function setUnexpectedErrorMessage($unexpectedErrorMessage)
{
$this->unexpectedErrorMessage = $unexpectedErrorMessage;
return $this;
}
/**
* @return int
*/
public function getUnexpectedErrorStatus()
{
return $this->unexpectedErrorStatus;
}
/**
* @param int $unexpectedErrorStatus
* @return $this
*/
public function setUnexpectedErrorStatus($unexpectedErrorStatus)
{
$this->unexpectedErrorStatus = $unexpectedErrorStatus;
return $this;
}
/**
* Parses GraphQL query string and returns Abstract Syntax Tree for this query
*
* @param string $query
* @return Language\AST\DocumentNode
* @throws \GraphQL\Error\SyntaxError
*/
public function parse($query)
{
return Parser::parse($query);
}
/**
* @return array
*/
public function getValidationRules()
{
if (null === $this->validationRules) {
$this->validationRules = DocumentValidator::allRules();
}
return $this->validationRules;
}
/**
* @param array $validationRules
* @return $this
*/
public function setValidationRules(array $validationRules)
{
$this->validationRules = $validationRules;
return $this;
}
/**
* EXPERIMENTAL!
* This method can be removed or changed in future versions without a prior notice.
*
* @return Resolution
*/
public function getTypeResolutionStrategy()
{
return $this->typeResolutionStrategy;
}
/**
* EXPERIMENTAL!
* This method can be removed or changed in future versions without a prior notice.
*
* @param Resolution $typeResolutionStrategy
* @return Server
*/
public function setTypeResolutionStrategy(Resolution $typeResolutionStrategy)
{
$this->assertSchemaNotSet('Type Resolution Strategy', __METHOD__);
$this->typeResolutionStrategy = $typeResolutionStrategy;
return $this;
}
/**
* @return PromiseAdapter|null
*/
public function getPromiseAdapter()
{
return $this->promiseAdapter;
}
/**
* See /docs/data-fetching.md#async-php
*
* @param PromiseAdapter $promiseAdapter
* @return Server
*/
public function setPromiseAdapter(PromiseAdapter $promiseAdapter)
{
if ($this->promiseAdapter && $promiseAdapter !== $this->promiseAdapter) {
throw new InvariantViolation("Cannot set promise adapter: Different adapter is already set");
}
$this->promiseAdapter = $promiseAdapter;
return $this;
}
/**
* Returns array with validation errors (empty when there are no validation errors)
*
* @param DocumentNode $query
* @return array
*/
public function validate(DocumentNode $query)
{
try {
$schema = $this->getSchema();
} catch (InvariantViolation $e) {
throw new InvariantViolation("Cannot validate, schema contains errors: {$e->getMessage()}", null, $e);
}
return DocumentValidator::validate($schema, $query, $this->validationRules);
}
/**
* Executes GraphQL query against this server and returns execution result
*
* @param string|DocumentNode $query
* @param array|null $variables
* @param string|null $operationName
* @return ExecutionResult
*/
public function executeQuery($query, array $variables = null, $operationName = null)
{
$this->phpErrors = [];
if ($this->debug & static::DEBUG_PHP_ERRORS) {
// Catch custom errors (to report them in query results)
set_error_handler(function($severity, $message, $file, $line) {
$this->phpErrors[] = new \ErrorException($message, 0, $severity, $file, $line);
});
}
if ($this->promiseAdapter) {
// TODO: inline GraphQL::executeAndReturnResult and pass promise adapter to executor constructor directly
$promiseAdapter = Executor::getPromiseAdapter();
Executor::setPromiseAdapter($this->promiseAdapter);
}
$result = GraphQL::executeAndReturnResult(
$this->getSchema(),
$query,
$this->getRootValue(),
$this->getContext(),
$variables,
$operationName
);
if (isset($promiseAdapter)) {
Executor::setPromiseAdapter($promiseAdapter);
}
// Add details about original exception in error entry (if any)
if ($this->debug & static::DEBUG_EXCEPTIONS) {
$result->setErrorFormatter([$this, 'formatError']);
}
// Add reported PHP errors to result (if any)
if (!empty($this->phpErrors) && ($this->debug & static::DEBUG_PHP_ERRORS)) {
$result->extensions['phpErrors'] = array_map($this->phpErrorFormatter, $this->phpErrors);
}
if ($this->debug & static::DEBUG_PHP_ERRORS) {
restore_error_handler();
}
return $result;
}
/**
* GraphQL HTTP endpoint compatible with express-graphql
*/
public function handleRequest()
{
try {
$httpStatus = 200;
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
$raw = $this->readInput();
$data = json_decode($raw, true);
Utils::invariant(
is_array($data),
"GraphQL Server expects JSON object with keys 'query' and 'variables', but got " . Utils::getVariableType($data)
);
} else {
$data = $_REQUEST ?: [];
}
$data += ['query' => null, 'variables' => null];
$result = $this->executeQuery($data['query'], (array) $data['variables'])->toArray();
} catch (\Exception $e) {
// This is only possible for schema creation errors and some very unpredictable errors,
// (all errors which occur during query execution are caught and included in final response)
$httpStatus = $this->unexpectedErrorStatus;
$error = new Error($this->unexpectedErrorMessage, null, null, null, null, $e);
$result = ['errors' => [$this->formatError($error)]];
} catch (\Throwable $e) {
$httpStatus = $this->unexpectedErrorStatus;
$error = new Error($this->unexpectedErrorMessage, null, null, null, null, $e);
$result = ['errors' => [$this->formatError($error)]];
}
$this->produceOutput($result, $httpStatus);
}
/**
* @param \Throwable $e
*/
private function formatException($e)
{
$formatter = $this->exceptionFormatter;
return $formatter($e);
}
/**
* @param Error $e
* @return array
*/
public function formatError(\GraphQL\Error\Error $e)
{
$result = $e->toSerializableArray();
if (($this->debug & static::DEBUG_EXCEPTIONS) && $e->getPrevious()) {
$result['exception'] = $this->formatException($e->getPrevious());
}
return $result;
}
protected function readInput()
{
return file_get_contents('php://input') ?: '';
}
protected function produceOutput(array $result, $httpStatus)
{
header('Content-Type: application/json', true, $httpStatus);
echo json_encode($result);
}
}
+205 -153
View File
@@ -1,6 +1,10 @@
<?php
declare(strict_types=1);
namespace GraphQL\Server;
use GraphQL\Error\DebugFlag;
use GraphQL\Error\Error;
use GraphQL\Error\FormattedError;
use GraphQL\Error\InvariantViolation;
@@ -14,16 +18,31 @@ use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\Parser;
use GraphQL\Utils\AST;
use GraphQL\Utils\Utils;
use JsonSerializable;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use function count;
use function file_get_contents;
use function header;
use function html_entity_decode;
use function is_array;
use function is_callable;
use function is_string;
use function json_decode;
use function json_encode;
use function json_last_error;
use function json_last_error_msg;
use function parse_str;
use function sprintf;
use function stripos;
/**
* Contains functionality that could be re-used by various server implementations
*/
class Helper
{
/**
* Parses HTTP request using PHP globals and returns GraphQL OperationParams
* contained in this request. For batched requests it returns an array of OperationParams.
@@ -39,42 +58,52 @@ class Helper
*
* For PSR-7 request parsing use `parsePsrRequest()` instead.
*
* @api
* @param callable|null $readRawBodyFn
* @return OperationParams|OperationParams[]
*
* @throws RequestError
*
* @api
*/
public function parseHttpRequest(callable $readRawBodyFn = null)
public function parseHttpRequest(?callable $readRawBodyFn = null)
{
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null;
$method = $_SERVER['REQUEST_METHOD'] ?? null;
$bodyParams = [];
$urlParams = $_GET;
$urlParams = $_GET;
if ($method === 'POST') {
$contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : null;
$contentType = $_SERVER['CONTENT_TYPE'] ?? null;
if ($contentType === null) {
throw new RequestError('Missing "Content-Type" header');
}
if (stripos($contentType, 'application/graphql') !== false) {
$rawBody = $readRawBodyFn ? $readRawBodyFn() : $this->readRawBody();
$bodyParams = ['query' => $rawBody ?: ''];
} else if (stripos($contentType, 'application/json') !== false) {
$rawBody = $readRawBodyFn ? $readRawBodyFn() : $this->readRawBody();
$bodyParams = json_decode($rawBody ?: '', true);
$rawBody = $readRawBodyFn
? $readRawBodyFn()
: $this->readRawBody();
$bodyParams = ['query' => $rawBody ?? ''];
} elseif (stripos($contentType, 'application/json') !== false) {
$rawBody = $readRawBodyFn ?
$readRawBodyFn()
: $this->readRawBody();
$bodyParams = json_decode($rawBody ?? '', true);
if (json_last_error()) {
throw new RequestError("Could not parse JSON: " . json_last_error_msg());
throw new RequestError('Could not parse JSON: ' . json_last_error_msg());
}
if (!is_array($bodyParams)) {
if (! is_array($bodyParams)) {
throw new RequestError(
"GraphQL Server expects JSON object or array, but got " .
'GraphQL Server expects JSON object or array, but got ' .
Utils::printSafeJson($bodyParams)
);
}
} else if (stripos($contentType, 'application/x-www-form-urlencoded') !== false) {
} elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false) {
$bodyParams = $_POST;
} elseif (stripos($contentType, 'multipart/form-data') !== false) {
$bodyParams = $_POST;
} else if (null === $contentType) {
throw new RequestError('Missing "Content-Type" header');
} else {
throw new RequestError("Unexpected content type: " . Utils::printSafeJson($contentType));
throw new RequestError('Unexpected content type: ' . Utils::printSafeJson($contentType));
}
}
@@ -87,22 +116,25 @@ class Helper
*
* Returned value is a suitable input for `executeOperation` or `executeBatch` (if array)
*
* @api
* @param string $method
* @param array $bodyParams
* @param array $queryParams
* @param string $method
* @param mixed[] $bodyParams
* @param mixed[] $queryParams
*
* @return OperationParams|OperationParams[]
*
* @throws RequestError
*
* @api
*/
public function parseRequestParams($method, array $bodyParams, array $queryParams)
{
if ($method === 'GET') {
$result = OperationParams::create($queryParams, true);
} else if ($method === 'POST') {
} elseif ($method === 'POST') {
if (isset($bodyParams[0])) {
$result = [];
foreach ($bodyParams as $index => $entry) {
$op = OperationParams::create($entry);
$op = OperationParams::create($entry);
$result[] = $op;
}
} else {
@@ -111,6 +143,7 @@ class Helper
} else {
throw new RequestError('HTTP Method "' . $method . '" is not supported');
}
return $result;
}
@@ -118,45 +151,49 @@ class Helper
* Checks validity of OperationParams extracted from HTTP request and returns an array of errors
* if params are invalid (or empty array when params are valid)
*
* @return array<int, RequestError>
*
* @api
* @param OperationParams $params
* @return Error[]
*/
public function validateOperationParams(OperationParams $params)
{
$errors = [];
if (!$params->query && !$params->queryId) {
if (! $params->query && ! $params->queryId) {
$errors[] = new RequestError('GraphQL Request must include at least one of those two parameters: "query" or "queryId"');
}
if ($params->query && $params->queryId) {
$errors[] = new RequestError('GraphQL Request parameters "query" and "queryId" are mutually exclusive');
}
if ($params->query !== null && (!is_string($params->query) || empty($params->query))) {
if ($params->query !== null && ! is_string($params->query)) {
$errors[] = new RequestError(
'GraphQL Request parameter "query" must be string, but got ' .
Utils::printSafeJson($params->query)
);
}
if ($params->queryId !== null && (!is_string($params->queryId) || empty($params->queryId))) {
if ($params->queryId !== null && ! is_string($params->queryId)) {
$errors[] = new RequestError(
'GraphQL Request parameter "queryId" must be string, but got ' .
Utils::printSafeJson($params->queryId)
);
}
if ($params->operation !== null && (!is_string($params->operation) || empty($params->operation))) {
if ($params->operation !== null && ! is_string($params->operation)) {
$errors[] = new RequestError(
'GraphQL Request parameter "operation" must be string, but got ' .
Utils::printSafeJson($params->operation)
);
}
if ($params->variables !== null && (!is_array($params->variables) || isset($params->variables[0]))) {
if ($params->variables !== null && (! is_array($params->variables) || isset($params->variables[0]))) {
$errors[] = new RequestError(
'GraphQL Request parameter "variables" must be object or JSON string parsed to object, but got ' .
Utils::printSafeJson($params->getOriginalInput('variables'))
);
}
return $errors;
}
@@ -164,16 +201,14 @@ class Helper
* Executes GraphQL operation with given server configuration and returns execution result
* (or promise when promise adapter is different from SyncPromiseAdapter)
*
* @api
* @param ServerConfig $config
* @param OperationParams $op
*
* @return ExecutionResult|Promise
*
* @api
*/
public function executeOperation(ServerConfig $config, OperationParams $op)
{
$promiseAdapter = $config->getPromiseAdapter() ?: Executor::getPromiseAdapter();
$result = $this->promiseToExecuteOperation($promiseAdapter, $config, $op);
$promiseAdapter = $config->getPromiseAdapter() ?? Executor::getPromiseAdapter();
$result = $this->promiseToExecuteOperation($promiseAdapter, $config, $op);
if ($promiseAdapter instanceof SyncPromiseAdapter) {
$result = $promiseAdapter->wait($result);
@@ -186,15 +221,16 @@ class Helper
* Executes batched GraphQL operations with shared promise queue
* (thus, effectively batching deferreds|promises of all queries at once)
*
* @api
* @param ServerConfig $config
* @param OperationParams[] $operations
* @return ExecutionResult[]|Promise
*
* @return ExecutionResult|ExecutionResult[]|Promise
*
* @api
*/
public function executeBatch(ServerConfig $config, array $operations)
{
$promiseAdapter = $config->getPromiseAdapter() ?: Executor::getPromiseAdapter();
$result = [];
$promiseAdapter = $config->getPromiseAdapter() ?? Executor::getPromiseAdapter();
$result = [];
foreach ($operations as $operation) {
$result[] = $this->promiseToExecuteOperation($promiseAdapter, $config, $operation, true);
@@ -206,46 +242,61 @@ class Helper
if ($promiseAdapter instanceof SyncPromiseAdapter) {
$result = $promiseAdapter->wait($result);
}
return $result;
}
/**
* @param PromiseAdapter $promiseAdapter
* @param ServerConfig $config
* @param OperationParams $op
* @param bool $isBatch
*
* @return Promise
*/
private function promiseToExecuteOperation(PromiseAdapter $promiseAdapter, ServerConfig $config, OperationParams $op, $isBatch = false)
{
private function promiseToExecuteOperation(
PromiseAdapter $promiseAdapter,
ServerConfig $config,
OperationParams $op,
$isBatch = false
) {
try {
if (!$config->getSchema()) {
throw new InvariantViolation("Schema is required for the server");
if ($config->getSchema() === null) {
throw new InvariantViolation('Schema is required for the server');
}
if ($isBatch && !$config->getQueryBatching()) {
throw new RequestError("Batched queries are not supported by this server");
if ($isBatch && ! $config->getQueryBatching()) {
throw new RequestError('Batched queries are not supported by this server');
}
$errors = $this->validateOperationParams($op);
if (!empty($errors)) {
$errors = Utils::map($errors, function(RequestError $err) {
return Error::createLocatedError($err, null, null);
});
if (count($errors) > 0) {
$errors = Utils::map(
$errors,
static function (RequestError $err) : Error {
return Error::createLocatedError($err, null, null);
}
);
return $promiseAdapter->createFulfilled(
new ExecutionResult(null, $errors)
);
}
$doc = $op->queryId ? $this->loadPersistedQuery($config, $op) : $op->query;
$doc = $op->queryId
? $this->loadPersistedQuery($config, $op)
: $op->query;
if (!$doc instanceof DocumentNode) {
if (! $doc instanceof DocumentNode) {
$doc = Parser::parse($doc);
}
$operationType = AST::getOperation($doc, $op->operation);
if ($op->isReadOnly() && $operationType !== 'query') {
throw new RequestError("GET supports only query operation");
if ($operationType === false) {
throw new RequestError('Failed to determine operation type');
}
if ($operationType !== 'query' && $op->isReadOnly()) {
throw new RequestError('GET supports only query operation');
}
$result = GraphQL::promiseToExecute(
@@ -259,7 +310,6 @@ class Helper
$config->getFieldResolver(),
$this->resolveValidationRules($config, $op, $doc, $operationType)
);
} catch (RequestError $e) {
$result = $promiseAdapter->createFulfilled(
new ExecutionResult(null, [Error::createLocatedError($e)])
@@ -270,16 +320,19 @@ class Helper
);
}
$applyErrorHandling = function (ExecutionResult $result) use ($config) {
$applyErrorHandling = static function (ExecutionResult $result) use ($config) : ExecutionResult {
if ($config->getErrorsHandler()) {
$result->setErrorsHandler($config->getErrorsHandler());
}
if ($config->getErrorFormatter() || $config->getDebug()) {
if ($config->getErrorFormatter() || $config->getDebugFlag() !== DebugFlag::NONE) {
$result->setErrorFormatter(
FormattedError::prepareFormatter($config->getErrorFormatter(),
$config->getDebug())
FormattedError::prepareFormatter(
$config->getErrorFormatter(),
$config->getDebugFlag()
)
);
}
return $result;
};
@@ -287,25 +340,24 @@ class Helper
}
/**
* @param ServerConfig $config
* @param OperationParams $op
* @return mixed
*
* @throws RequestError
*/
private function loadPersistedQuery(ServerConfig $config, OperationParams $op)
private function loadPersistedQuery(ServerConfig $config, OperationParams $operationParams)
{
// Load query if we got persisted query id:
$loader = $config->getPersistentQueryLoader();
if (!$loader) {
throw new RequestError("Persisted queries are not supported by this server");
if ($loader === null) {
throw new RequestError('Persisted queries are not supported by this server');
}
$source = $loader($op->queryId, $op);
$source = $loader($operationParams->queryId, $operationParams);
if (!is_string($source) && !$source instanceof DocumentNode) {
if (! is_string($source) && ! $source instanceof DocumentNode) {
throw new InvariantViolation(sprintf(
"Persistent query loader must return query string or instance of %s but got: %s",
'Persistent query loader must return query string or instance of %s but got: %s',
DocumentNode::class,
Utils::printSafe($source)
));
@@ -315,23 +367,25 @@ class Helper
}
/**
* @param ServerConfig $config
* @param OperationParams $params
* @param DocumentNode $doc
* @param $operationType
* @return array
* @param string $operationType
*
* @return mixed[]|null
*/
private function resolveValidationRules(ServerConfig $config, OperationParams $params, DocumentNode $doc, $operationType)
{
private function resolveValidationRules(
ServerConfig $config,
OperationParams $params,
DocumentNode $doc,
$operationType
) {
// Allow customizing validation rules per operation:
$validationRules = $config->getValidationRules();
if (is_callable($validationRules)) {
$validationRules = $validationRules($params, $doc, $operationType);
if (!is_array($validationRules)) {
if (! is_array($validationRules)) {
throw new InvariantViolation(sprintf(
"Expecting validation rules to be array or callable returning array, but got: %s",
'Expecting validation rules to be array or callable returning array, but got: %s',
Utils::printSafe($validationRules)
));
}
@@ -341,35 +395,33 @@ class Helper
}
/**
* @param ServerConfig $config
* @param OperationParams $params
* @param DocumentNode $doc
* @param $operationType
* @return mixed
*/
private function resolveRootValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, $operationType)
private function resolveRootValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, string $operationType)
{
$root = $config->getRootValue();
$rootValue = $config->getRootValue();
if ($root instanceof \Closure) {
$root = $root($params, $doc, $operationType);
if (is_callable($rootValue)) {
$rootValue = $rootValue($params, $doc, $operationType);
}
return $root;
return $rootValue;
}
/**
* @param ServerConfig $config
* @param OperationParams $params
* @param DocumentNode $doc
* @param $operationType
* @param string $operationType
*
* @return mixed
*/
private function resolveContextValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, $operationType)
{
private function resolveContextValue(
ServerConfig $config,
OperationParams $params,
DocumentNode $doc,
$operationType
) {
$context = $config->getContext();
if ($context instanceof \Closure) {
if (is_callable($context)) {
$context = $context($params, $doc, $operationType);
}
@@ -379,14 +431,15 @@ class Helper
/**
* Send response using standard PHP `header()` and `echo`.
*
* @api
* @param Promise|ExecutionResult|ExecutionResult[] $result
* @param bool $exitWhenDone
* @param bool $exitWhenDone
*
* @api
*/
public function sendResponse($result, $exitWhenDone = false)
{
if ($result instanceof Promise) {
$result->then(function($actualResult) use ($exitWhenDone) {
$result->then(function ($actualResult) use ($exitWhenDone) : void {
$this->doSendResponse($actualResult, $exitWhenDone);
});
} else {
@@ -394,10 +447,6 @@ class Helper
}
}
/**
* @param $result
* @param $exitWhenDone
*/
private function doSendResponse($result, $exitWhenDone)
{
$httpStatus = $this->resolveHttpStatus($result);
@@ -405,9 +454,9 @@ class Helper
}
/**
* @param array|\JsonSerializable $jsonSerializable
* @param int $httpStatus
* @param bool $exitWhenDone
* @param mixed[]|JsonSerializable $jsonSerializable
* @param int $httpStatus
* @param bool $exitWhenDone
*/
public function emitResponse($jsonSerializable, $httpStatus, $exitWhenDone)
{
@@ -429,119 +478,122 @@ class Helper
}
/**
* @param $result
* @param ExecutionResult|mixed[] $result
*
* @return int
*/
private function resolveHttpStatus($result)
{
if (is_array($result) && isset($result[0])) {
Utils::each($result, function ($executionResult, $index) {
if (!$executionResult instanceof ExecutionResult) {
throw new InvariantViolation(sprintf(
"Expecting every entry of batched query result to be instance of %s but entry at position %d is %s",
ExecutionResult::class,
$index,
Utils::printSafe($executionResult)
));
Utils::each(
$result,
static function ($executionResult, $index) : void {
if (! $executionResult instanceof ExecutionResult) {
throw new InvariantViolation(sprintf(
'Expecting every entry of batched query result to be instance of %s but entry at position %d is %s',
ExecutionResult::class,
$index,
Utils::printSafe($executionResult)
));
}
}
});
);
$httpStatus = 200;
} else {
if (!$result instanceof ExecutionResult) {
if (! $result instanceof ExecutionResult) {
throw new InvariantViolation(sprintf(
"Expecting query result to be instance of %s but got %s",
'Expecting query result to be instance of %s but got %s',
ExecutionResult::class,
Utils::printSafe($result)
));
}
if ($result->data === null && !empty($result->errors)) {
if ($result->data === null && count($result->errors) > 0) {
$httpStatus = 400;
} else {
$httpStatus = 200;
}
}
return $httpStatus;
}
/**
* Converts PSR-7 request to OperationParams[]
*
* @api
* @param ServerRequestInterface $request
* @return array|Helper
* @return OperationParams[]|OperationParams
*
* @throws RequestError
*
* @api
*/
public function parsePsrRequest(ServerRequestInterface $request)
public function parsePsrRequest(RequestInterface $request)
{
if ($request->getMethod() === 'GET') {
$bodyParams = [];
} else {
$contentType = $request->getHeader('content-type');
if (!isset($contentType[0])) {
if (! isset($contentType[0])) {
throw new RequestError('Missing "Content-Type" header');
}
if (stripos('application/graphql', $contentType[0]) !== false) {
$bodyParams = ['query' => $request->getBody()->getContents()];
} else if (stripos('application/json', $contentType[0]) !== false) {
$bodyParams = $request->getParsedBody();
if (stripos($contentType[0], 'application/graphql') !== false) {
$bodyParams = ['query' => (string) $request->getBody()];
} elseif (stripos($contentType[0], 'application/json') !== false) {
$bodyParams = $request instanceof ServerRequestInterface
? $request->getParsedBody()
: json_decode((string) $request->getBody(), true);
if (null === $bodyParams) {
if ($bodyParams === null) {
throw new InvariantViolation(
"PSR-7 request is expected to provide parsed body for \"application/json\" requests but got null"
$request instanceof ServerRequestInterface
? 'Expected to receive a parsed body for "application/json" PSR-7 request but got null'
: 'Expected to receive a JSON array in body for "application/json" PSR-7 request'
);
}
// Try parsing ourselves if PSR-7 implementation doesn't parse JSON automatically
if (is_array($bodyParams) && empty($bodyParams)) {
$bodyParams = json_decode($request->getBody(), true);
if (json_last_error()) {
throw new RequestError("Could not parse JSON: " . json_last_error_msg());
}
}
if (!is_array($bodyParams)) {
if (! is_array($bodyParams)) {
throw new RequestError(
"GraphQL Server expects JSON object or array, but got " .
'GraphQL Server expects JSON object or array, but got ' .
Utils::printSafeJson($bodyParams)
);
}
} else {
$bodyParams = $request->getParsedBody();
parse_str((string) $request->getBody(), $bodyParams);
if (!is_array($bodyParams)) {
throw new RequestError("Unexpected content type: " . Utils::printSafeJson($contentType[0]));
if (! is_array($bodyParams)) {
throw new RequestError('Unexpected content type: ' . Utils::printSafeJson($contentType[0]));
}
}
}
parse_str(html_entity_decode($request->getUri()->getQuery()), $queryParams);
return $this->parseRequestParams(
$request->getMethod(),
$bodyParams,
$request->getQueryParams()
$queryParams
);
}
/**
* Converts query execution result to PSR-7 response
*
* @api
* @param Promise|ExecutionResult|ExecutionResult[] $result
* @param ResponseInterface $response
* @param StreamInterface $writableBodyStream
*
* @return Promise|ResponseInterface
*
* @api
*/
public function toPsrResponse($result, ResponseInterface $response, StreamInterface $writableBodyStream)
{
if ($result instanceof Promise) {
return $result->then(function($actualResult) use ($response, $writableBodyStream) {
return $result->then(function ($actualResult) use ($response, $writableBodyStream) {
return $this->doConvertToPsrResponse($actualResult, $response, $writableBodyStream);
});
} else {
return $this->doConvertToPsrResponse($result, $response, $writableBodyStream);
}
return $this->doConvertToPsrResponse($result, $response, $writableBodyStream);
}
private function doConvertToPsrResponse($result, ResponseInterface $response, StreamInterface $writableBodyStream)
Loaded 100 of 2036 files, more files were not shown because too many files have changed in this diff. Show more