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

+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;
}