Fix CS in src/Utils

This commit is contained in:
Simon Podlipsky 2018-09-26 10:55:09 +02:00
parent 18a5639cb7
commit e664c4455e
No known key found for this signature in database
GPG Key ID: 725C2BD962B42663
11 changed files with 213 additions and 113 deletions

View File

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace GraphQL\Utils; namespace GraphQL\Utils;
use ArrayAccess;
use Exception;
use GraphQL\Error\Error; use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation; use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\BooleanValueNode;
@ -36,6 +38,9 @@ use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema; use GraphQL\Type\Schema;
use stdClass;
use Throwable;
use Traversable;
use function array_combine; use function array_combine;
use function array_key_exists; use function array_key_exists;
use function array_map; use function array_map;
@ -77,8 +82,9 @@ class AST
* *
* This is a reverse operation for AST::toArray($node) * This is a reverse operation for AST::toArray($node)
* *
* @api
* @param mixed[] $node * @param mixed[] $node
*
* @api
*/ */
public static function fromArray(array $node) : Node public static function fromArray(array $node) : Node
{ {
@ -114,8 +120,9 @@ class AST
/** /**
* Convert AST node to serializable array * Convert AST node to serializable array
* *
* @api
* @return mixed[] * @return mixed[]
*
* @api
*/ */
public static function toArray(Node $node) public static function toArray(Node $node)
{ {
@ -140,9 +147,11 @@ class AST
* | Mixed | Enum Value | * | Mixed | Enum Value |
* | null | NullValue | * | null | NullValue |
* *
* @api
* @param Type|mixed|null $value * @param Type|mixed|null $value
*
* @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode
*
* @api
*/ */
public static function astFromValue($value, InputType $type) public static function astFromValue($value, InputType $type)
{ {
@ -163,7 +172,7 @@ class AST
// the value is not an array, convert the value using the list's item type. // the value is not an array, convert the value using the list's item type.
if ($type instanceof ListOfType) { if ($type instanceof ListOfType) {
$itemType = $type->getWrappedType(); $itemType = $type->getWrappedType();
if (is_array($value) || ($value instanceof \Traversable)) { if (is_array($value) || ($value instanceof Traversable)) {
$valuesNodes = []; $valuesNodes = [];
foreach ($value as $item) { foreach ($value as $item) {
$itemNode = self::astFromValue($item, $itemType); $itemNode = self::astFromValue($item, $itemType);
@ -184,7 +193,7 @@ class AST
// in the PHP object according to the fields in the input type. // in the PHP object according to the fields in the input type.
if ($type instanceof InputObjectType) { if ($type instanceof InputObjectType) {
$isArray = is_array($value); $isArray = is_array($value);
$isArrayLike = $isArray || $value instanceof \ArrayAccess; $isArrayLike = $isArray || $value instanceof ArrayAccess;
if ($value === null || (! $isArrayLike && ! is_object($value))) { if ($value === null || (! $isArrayLike && ! is_object($value))) {
return null; return null;
} }
@ -204,7 +213,7 @@ class AST
} elseif ($isArray) { } elseif ($isArray) {
$fieldExists = array_key_exists($fieldName, $value); $fieldExists = array_key_exists($fieldName, $value);
} elseif ($isArrayLike) { } elseif ($isArrayLike) {
/** @var \ArrayAccess $value */ /** @var ArrayAccess $value */
$fieldExists = $value->offsetExists($fieldName); $fieldExists = $value->offsetExists($fieldName);
} else { } else {
$fieldExists = property_exists($value, $fieldName); $fieldExists = property_exists($value, $fieldName);
@ -234,12 +243,12 @@ class AST
// to an externally represented value before converting into an AST. // to an externally represented value before converting into an AST.
try { try {
$serialized = $type->serialize($value); $serialized = $type->serialize($value);
} catch (\Exception $error) { } catch (Exception $error) {
if ($error instanceof Error && $type instanceof EnumType) { if ($error instanceof Error && $type instanceof EnumType) {
return null; return null;
} }
throw $error; throw $error;
} catch (\Throwable $error) { } catch (Throwable $error) {
if ($error instanceof Error && $type instanceof EnumType) { if ($error instanceof Error && $type instanceof EnumType) {
return null; return null;
} }
@ -304,13 +313,16 @@ class AST
* | Enum Value | Mixed | * | Enum Value | Mixed |
* | Null Value | null | * | Null Value | null |
* *
* @api
* @param ValueNode|null $valueNode * @param ValueNode|null $valueNode
* @param mixed[]|null $variables * @param mixed[]|null $variables
* @return mixed[]|null|\stdClass *
* @throws \Exception * @return mixed[]|stdClass|null
*
* @throws Exception
*
* @api
*/ */
public static function valueFromAST($valueNode, InputType $type, $variables = null) public static function valueFromAST($valueNode, InputType $type, ?array $variables = null)
{ {
$undefined = Utils::undefined(); $undefined = Utils::undefined();
@ -393,7 +405,7 @@ class AST
$fields = $type->getFields(); $fields = $type->getFields();
$fieldNodes = Utils::keyMap( $fieldNodes = Utils::keyMap(
$valueNode->fields, $valueNode->fields,
function ($field) { static function ($field) {
return $field->name->value; return $field->name->value;
} }
); );
@ -442,9 +454,9 @@ class AST
// no value is returned. // no value is returned.
try { try {
return $type->parseLiteral($valueNode, $variables); return $type->parseLiteral($valueNode, $variables);
} catch (\Exception $error) { } catch (Exception $error) {
return $undefined; return $undefined;
} catch (\Throwable $error) { } catch (Throwable $error) {
return $undefined; return $undefined;
} }
} }
@ -455,8 +467,10 @@ class AST
/** /**
* Returns true if the provided valueNode is a variable which is not defined * Returns true if the provided valueNode is a variable which is not defined
* in the set of variables. * in the set of variables.
*
* @param ValueNode $valueNode * @param ValueNode $valueNode
* @param mixed[] $variables * @param mixed[] $variables
*
* @return bool * @return bool
*/ */
private static function isMissingVariable($valueNode, $variables) private static function isMissingVariable($valueNode, $variables)
@ -481,11 +495,14 @@ class AST
* | Enum | Mixed | * | Enum | Mixed |
* | Null | null | * | Null | null |
* *
* @api
* @param Node $valueNode * @param Node $valueNode
* @param mixed[]|null $variables * @param mixed[]|null $variables
*
* @return mixed * @return mixed
* @throws \Exception *
* @throws Exception
*
* @api
*/ */
public static function valueFromASTUntyped($valueNode, ?array $variables = null) public static function valueFromASTUntyped($valueNode, ?array $variables = null)
{ {
@ -502,7 +519,7 @@ class AST
return $valueNode->value; return $valueNode->value;
case $valueNode instanceof ListValueNode: case $valueNode instanceof ListValueNode:
return array_map( return array_map(
function ($node) use ($variables) { static function ($node) use ($variables) {
return self::valueFromASTUntyped($node, $variables); return self::valueFromASTUntyped($node, $variables);
}, },
iterator_to_array($valueNode->values) iterator_to_array($valueNode->values)
@ -510,13 +527,13 @@ class AST
case $valueNode instanceof ObjectValueNode: case $valueNode instanceof ObjectValueNode:
return array_combine( return array_combine(
array_map( array_map(
function ($field) { static function ($field) {
return $field->name->value; return $field->name->value;
}, },
iterator_to_array($valueNode->fields) iterator_to_array($valueNode->fields)
), ),
array_map( array_map(
function ($field) use ($variables) { static function ($field) use ($variables) {
return self::valueFromASTUntyped($field->value, $variables); return self::valueFromASTUntyped($field->value, $variables);
}, },
iterator_to_array($valueNode->fields) iterator_to_array($valueNode->fields)
@ -525,7 +542,7 @@ class AST
case $valueNode instanceof VariableNode: case $valueNode instanceof VariableNode:
$variableName = $valueNode->name->value; $variableName = $valueNode->name->value;
return ($variables && isset($variables[$variableName])) return $variables && isset($variables[$variableName])
? $variables[$variableName] ? $variables[$variableName]
: null; : null;
} }
@ -536,10 +553,13 @@ class AST
/** /**
* Returns type definition for given AST Type node * Returns type definition for given AST Type node
* *
* @api
* @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
*
* @return Type|null * @return Type|null
* @throws \Exception *
* @throws Exception
*
* @api
*/ */
public static function typeFromAST(Schema $schema, $inputTypeNode) public static function typeFromAST(Schema $schema, $inputTypeNode)
{ {
@ -563,9 +583,11 @@ class AST
/** /**
* Returns operation type ("query", "mutation" or "subscription") given a document and operation name * Returns operation type ("query", "mutation" or "subscription") given a document and operation name
* *
* @api
* @param string $operationName * @param string $operationName
*
* @return bool * @return bool
*
* @api
*/ */
public static function getOperation(DocumentNode $document, $operationName = null) public static function getOperation(DocumentNode $document, $operationName = null)
{ {

View File

@ -34,6 +34,7 @@ use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Definition\UnionType;
use Throwable;
use function array_reverse; use function array_reverse;
use function implode; use function implode;
use function is_array; use function is_array;
@ -82,7 +83,7 @@ class ASTDefinitionBuilder
'description' => $this->getDescription($directiveNode), 'description' => $this->getDescription($directiveNode),
'locations' => Utils::map( 'locations' => Utils::map(
$directiveNode->locations, $directiveNode->locations,
function ($node) { static function ($node) {
return $node->value; return $node->value;
} }
), ),
@ -135,7 +136,7 @@ class ASTDefinitionBuilder
{ {
return Utils::keyValMap( return Utils::keyValMap(
$values, $values,
function ($value) { static function ($value) {
return $value->name->value; return $value->name->value;
}, },
function ($value) { function ($value) {
@ -160,6 +161,7 @@ class ASTDefinitionBuilder
/** /**
* @return Type|InputType * @return Type|InputType
*
* @throws Error * @throws Error
*/ */
private function internalBuildWrappedType(TypeNode $typeNode) private function internalBuildWrappedType(TypeNode $typeNode)
@ -171,7 +173,9 @@ class ASTDefinitionBuilder
/** /**
* @param string|NamedTypeNode $ref * @param string|NamedTypeNode $ref
*
* @return Type * @return Type
*
* @throws Error * @throws Error
*/ */
public function buildType($ref) public function buildType($ref)
@ -186,7 +190,9 @@ class ASTDefinitionBuilder
/** /**
* @param string $typeName * @param string $typeName
* @param NamedTypeNode|null $typeNode * @param NamedTypeNode|null $typeNode
*
* @return Type * @return Type
*
* @throws Error * @throws Error
*/ */
private function internalBuildType($typeName, $typeNode = null) private function internalBuildType($typeName, $typeNode = null)
@ -198,7 +204,7 @@ class ASTDefinitionBuilder
$fn = $this->typeConfigDecorator; $fn = $this->typeConfigDecorator;
try { try {
$config = $fn($type->config, $this->typeDefintionsMap[$typeName], $this->typeDefintionsMap); $config = $fn($type->config, $this->typeDefintionsMap[$typeName], $this->typeDefintionsMap);
} catch (\Throwable $e) { } catch (Throwable $e) {
throw new Error( throw new Error(
sprintf('Type config decorator passed to %s threw an error ', static::class) . sprintf('Type config decorator passed to %s threw an error ', static::class) .
sprintf('when building %s type: %s', $typeName, $e->getMessage()), sprintf('when building %s type: %s', $typeName, $e->getMessage()),
@ -232,7 +238,9 @@ class ASTDefinitionBuilder
/** /**
* @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeDefinitionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode|UnionTypeDefinitionNode $def * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeDefinitionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode|UnionTypeDefinitionNode $def
*
* @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType * @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType
*
* @throws Error * @throws Error
*/ */
private function makeSchemaDef($def) private function makeSchemaDef($def)
@ -280,7 +288,7 @@ class ASTDefinitionBuilder
return $def->fields return $def->fields
? Utils::keyValMap( ? Utils::keyValMap(
$def->fields, $def->fields,
function ($field) { static function ($field) {
return $field->name->value; return $field->name->value;
}, },
function ($field) { function ($field) {
@ -309,6 +317,7 @@ class ASTDefinitionBuilder
* deprecation reason. * deprecation reason.
* *
* @param EnumValueDefinitionNode | FieldDefinitionNode $node * @param EnumValueDefinitionNode | FieldDefinitionNode $node
*
* @return string * @return string
*/ */
private function getDeprecationReason($node) private function getDeprecationReason($node)
@ -357,7 +366,7 @@ class ASTDefinitionBuilder
'values' => $def->values 'values' => $def->values
? Utils::keyValMap( ? Utils::keyValMap(
$def->values, $def->values,
function ($enumValue) { static function ($enumValue) {
return $enumValue->name->value; return $enumValue->name->value;
}, },
function ($enumValue) { function ($enumValue) {
@ -399,7 +408,7 @@ class ASTDefinitionBuilder
'name' => $def->name->value, 'name' => $def->name->value,
'description' => $this->getDescription($def), 'description' => $this->getDescription($def),
'astNode' => $def, 'astNode' => $def,
'serialize' => function ($value) { 'serialize' => static function ($value) {
return $value; return $value;
}, },
]); ]);
@ -422,7 +431,9 @@ class ASTDefinitionBuilder
/** /**
* @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeExtensionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode $def * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeExtensionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode $def
* @param mixed[] $config * @param mixed[] $config
*
* @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType * @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType
*
* @throws Error * @throws Error
*/ */
private function makeSchemaDefFromConfig($def, array $config) private function makeSchemaDefFromConfig($def, array $config)
@ -450,6 +461,7 @@ class ASTDefinitionBuilder
/** /**
* @param TypeNode|ListTypeNode|NonNullTypeNode $typeNode * @param TypeNode|ListTypeNode|NonNullTypeNode $typeNode
*
* @return TypeNode * @return TypeNode
*/ */
private function getNamedTypeNode(TypeNode $typeNode) private function getNamedTypeNode(TypeNode $typeNode)
@ -464,6 +476,7 @@ class ASTDefinitionBuilder
/** /**
* @param TypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * @param TypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
*
* @return Type * @return Type
*/ */
private function buildWrappedType(Type $innerType, TypeNode $inputTypeNode) private function buildWrappedType(Type $innerType, TypeNode $inputTypeNode)

View File

@ -21,6 +21,7 @@ use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Schema; use GraphQL\Type\Schema;
use TypeError;
use function array_flip; use function array_flip;
use function array_key_exists; use function array_key_exists;
use function array_keys; use function array_keys;
@ -141,7 +142,7 @@ class BreakingChangesFinder
/** /**
* @return string * @return string
* *
* @throws \TypeError * @throws TypeError
*/ */
private static function typeKindName(Type $type) private static function typeKindName(Type $type)
{ {
@ -169,7 +170,7 @@ class BreakingChangesFinder
return 'an Input type'; return 'an Input type';
} }
throw new \TypeError('unknown type ' . $type->name); throw new TypeError('unknown type ' . $type->name);
} }
/** /**
@ -340,7 +341,6 @@ class BreakingChangesFinder
} }
/** /**
*
* @return bool * @return bool
*/ */
private static function isChangeSafeForInputObjectFieldOrFieldArg( private static function isChangeSafeForInputObjectFieldOrFieldArg(
@ -370,8 +370,8 @@ class BreakingChangesFinder
$newType->getWrappedType() $newType->getWrappedType()
)) || )) ||
// moving from non-null to nullable of the same underlying type is safe // moving from non-null to nullable of the same underlying type is safe
(! ($newType instanceof NonNull) && ! ($newType instanceof NonNull) &&
self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType)); self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType);
} }
return false; return false;
@ -492,7 +492,7 @@ class BreakingChangesFinder
$newArgs = $newTypeFields[$fieldName]->args; $newArgs = $newTypeFields[$fieldName]->args;
$newArgDef = Utils::find( $newArgDef = Utils::find(
$newArgs, $newArgs,
function ($arg) use ($oldArgDef) { static function ($arg) use ($oldArgDef) {
return $arg->name === $oldArgDef->name; return $arg->name === $oldArgDef->name;
} }
); );
@ -531,7 +531,7 @@ class BreakingChangesFinder
$oldArgs = $oldTypeFields[$fieldName]->args; $oldArgs = $oldTypeFields[$fieldName]->args;
$oldArgDef = Utils::find( $oldArgDef = Utils::find(
$oldArgs, $oldArgs,
function ($arg) use ($newArgDef) { static function ($arg) use ($newArgDef) {
return $arg->name === $newArgDef->name; return $arg->name === $newArgDef->name;
} }
); );
@ -586,7 +586,7 @@ class BreakingChangesFinder
foreach ($oldInterfaces as $oldInterface) { foreach ($oldInterfaces as $oldInterface) {
if (Utils::find( if (Utils::find(
$newInterfaces, $newInterfaces,
function (InterfaceType $interface) use ($oldInterface) { static function (InterfaceType $interface) use ($oldInterface) {
return $interface->name === $oldInterface->name; return $interface->name === $oldInterface->name;
} }
)) { )) {
@ -629,7 +629,7 @@ class BreakingChangesFinder
{ {
return Utils::keyMap( return Utils::keyMap(
$schema->getDirectives(), $schema->getDirectives(),
function ($dir) { static function ($dir) {
return $dir->name; return $dir->name;
} }
); );
@ -678,7 +678,7 @@ class BreakingChangesFinder
{ {
return Utils::keyMap( return Utils::keyMap(
$directive->args ?: [], $directive->args ?: [],
function ($arg) { static function ($arg) {
return $arg->name; return $arg->name;
} }
); );
@ -831,7 +831,6 @@ class BreakingChangesFinder
} }
/** /**
*
* @return string[][] * @return string[][]
*/ */
public static function findInterfacesAddedToObjectTypes( public static function findInterfacesAddedToObjectTypes(
@ -853,7 +852,7 @@ class BreakingChangesFinder
foreach ($newInterfaces as $newInterface) { foreach ($newInterfaces as $newInterface) {
if (Utils::find( if (Utils::find(
$oldInterfaces, $oldInterfaces,
function (InterfaceType $interface) use ($newInterface) { static function (InterfaceType $interface) use ($newInterface) {
return $interface->name === $newInterface->name; return $interface->name === $newInterface->name;
} }
)) { )) {

View File

@ -49,10 +49,12 @@ class BuildSchema
* A helper function to build a GraphQLSchema directly from a source * A helper function to build a GraphQLSchema directly from a source
* document. * document.
* *
* @api
* @param DocumentNode|Source|string $source * @param DocumentNode|Source|string $source
* @param bool[] $options * @param bool[] $options
*
* @return Schema * @return Schema
*
* @api
*/ */
public static function build($source, ?callable $typeConfigDecorator = null, array $options = []) public static function build($source, ?callable $typeConfigDecorator = null, array $options = [])
{ {
@ -76,11 +78,13 @@ class BuildSchema
* - commentDescriptions: * - commentDescriptions:
* Provide true to use preceding comments as the description. * Provide true to use preceding comments as the description.
* *
* @param bool[] $options
*
* @return Schema
*
* @throws Error
* *
* @api * @api
* @param bool[] $options
* @return Schema
* @throws Error
*/ */
public static function buildAST(DocumentNode $ast, ?callable $typeConfigDecorator = null, array $options = []) public static function buildAST(DocumentNode $ast, ?callable $typeConfigDecorator = null, array $options = [])
{ {
@ -134,14 +138,14 @@ class BuildSchema
$defintionBuilder = new ASTDefinitionBuilder( $defintionBuilder = new ASTDefinitionBuilder(
$this->nodeMap, $this->nodeMap,
$this->options, $this->options,
function ($typeName) { static function ($typeName) {
throw new Error('Type "' . $typeName . '" not found in document.'); throw new Error('Type "' . $typeName . '" not found in document.');
}, },
$this->typeConfigDecorator $this->typeConfigDecorator
); );
$directives = array_map( $directives = array_map(
function ($def) use ($defintionBuilder) { static function ($def) use ($defintionBuilder) {
return $defintionBuilder->buildDirective($def); return $defintionBuilder->buildDirective($def);
}, },
$directiveDefs $directiveDefs
@ -150,7 +154,7 @@ class BuildSchema
// If specified directives were not explicitly declared, add them. // If specified directives were not explicitly declared, add them.
$skip = array_reduce( $skip = array_reduce(
$directives, $directives,
function ($hasSkip, $directive) { static function ($hasSkip, $directive) {
return $hasSkip || $directive->name === 'skip'; return $hasSkip || $directive->name === 'skip';
} }
); );
@ -160,7 +164,7 @@ class BuildSchema
$include = array_reduce( $include = array_reduce(
$directives, $directives,
function ($hasInclude, $directive) { static function ($hasInclude, $directive) {
return $hasInclude || $directive->name === 'include'; return $hasInclude || $directive->name === 'include';
} }
); );
@ -170,7 +174,7 @@ class BuildSchema
$deprecated = array_reduce( $deprecated = array_reduce(
$directives, $directives,
function ($hasDeprecated, $directive) { static function ($hasDeprecated, $directive) {
return $hasDeprecated || $directive->name === 'deprecated'; return $hasDeprecated || $directive->name === 'deprecated';
} }
); );
@ -182,7 +186,7 @@ class BuildSchema
// typed values below, that would throw immediately while type system // typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results. // validation with validateSchema() will produce more actionable results.
$schema = new Schema([ return new Schema([
'query' => isset($operationTypes['query']) 'query' => isset($operationTypes['query'])
? $defintionBuilder->buildType($operationTypes['query']) ? $defintionBuilder->buildType($operationTypes['query'])
: null, : null,
@ -192,7 +196,7 @@ class BuildSchema
'subscription' => isset($operationTypes['subscription']) 'subscription' => isset($operationTypes['subscription'])
? $defintionBuilder->buildType($operationTypes['subscription']) ? $defintionBuilder->buildType($operationTypes['subscription'])
: null, : null,
'typeLoader' => function ($name) use ($defintionBuilder) { 'typeLoader' => static function ($name) use ($defintionBuilder) {
return $defintionBuilder->buildType($name); return $defintionBuilder->buildType($name);
}, },
'directives' => $directives, 'directives' => $directives,
@ -206,13 +210,13 @@ class BuildSchema
return $types; return $types;
}, },
]); ]);
return $schema;
} }
/** /**
* @param SchemaDefinitionNode $schemaDef * @param SchemaDefinitionNode $schemaDef
*
* @return string[] * @return string[]
*
* @throws Error * @throws Error
*/ */
private function getOperationTypes($schemaDef) private function getOperationTypes($schemaDef)

View File

@ -4,7 +4,10 @@ declare(strict_types=1);
namespace GraphQL\Utils; namespace GraphQL\Utils;
use ArrayAccess;
use GraphQL\Type\Definition\EnumValueDefinition; use GraphQL\Type\Definition\EnumValueDefinition;
use InvalidArgumentException;
use SplObjectStorage;
use function array_key_exists; use function array_key_exists;
use function array_search; use function array_search;
use function array_splice; use function array_splice;
@ -22,7 +25,7 @@ use function is_string;
* *
* Class MixedStore * Class MixedStore
*/ */
class MixedStore implements \ArrayAccess class MixedStore implements ArrayAccess
{ {
/** @var EnumValueDefinition[] */ /** @var EnumValueDefinition[] */
private $standardStore; private $standardStore;
@ -30,7 +33,7 @@ class MixedStore implements \ArrayAccess
/** @var mixed[] */ /** @var mixed[] */
private $floatStore; private $floatStore;
/** @var \SplObjectStorage */ /** @var SplObjectStorage */
private $objectStore; private $objectStore;
/** @var callable[] */ /** @var callable[] */
@ -67,7 +70,7 @@ class MixedStore implements \ArrayAccess
{ {
$this->standardStore = []; $this->standardStore = [];
$this->floatStore = []; $this->floatStore = [];
$this->objectStore = new \SplObjectStorage(); $this->objectStore = new SplObjectStorage();
$this->arrayKeys = []; $this->arrayKeys = [];
$this->arrayValues = []; $this->arrayValues = [];
$this->nullValueIsSet = false; $this->nullValueIsSet = false;
@ -77,10 +80,13 @@ class MixedStore implements \ArrayAccess
/** /**
* Whether a offset exists * Whether a offset exists
*
* @link http://php.net/manual/en/arrayaccess.offsetexists.php * @link http://php.net/manual/en/arrayaccess.offsetexists.php
*
* @param mixed $offset <p> * @param mixed $offset <p>
* An offset to check for. * An offset to check for.
* </p> * </p>
*
* @return bool true on success or false on failure. * @return bool true on success or false on failure.
* </p> * </p>
* <p> * <p>
@ -122,10 +128,13 @@ class MixedStore implements \ArrayAccess
/** /**
* Offset to retrieve * Offset to retrieve
*
* @link http://php.net/manual/en/arrayaccess.offsetget.php * @link http://php.net/manual/en/arrayaccess.offsetget.php
*
* @param mixed $offset <p> * @param mixed $offset <p>
* The offset to retrieve. * The offset to retrieve.
* </p> * </p>
*
* @return mixed Can return all value types. * @return mixed Can return all value types.
*/ */
public function offsetGet($offset) public function offsetGet($offset)
@ -165,13 +174,16 @@ class MixedStore implements \ArrayAccess
/** /**
* Offset to set * Offset to set
*
* @link http://php.net/manual/en/arrayaccess.offsetset.php * @link http://php.net/manual/en/arrayaccess.offsetset.php
*
* @param mixed $offset <p> * @param mixed $offset <p>
* The offset to assign the value to. * The offset to assign the value to.
* </p> * </p>
* @param mixed $value <p> * @param mixed $value <p>
* The value to set. * The value to set.
* </p> * </p>
*
* @return void * @return void
*/ */
public function offsetSet($offset, $value) public function offsetSet($offset, $value)
@ -195,16 +207,19 @@ class MixedStore implements \ArrayAccess
$this->nullValue = $value; $this->nullValue = $value;
$this->nullValueIsSet = true; $this->nullValueIsSet = true;
} else { } else {
throw new \InvalidArgumentException('Unexpected offset type: ' . Utils::printSafe($offset)); throw new InvalidArgumentException('Unexpected offset type: ' . Utils::printSafe($offset));
} }
} }
/** /**
* Offset to unset * Offset to unset
*
* @link http://php.net/manual/en/arrayaccess.offsetunset.php * @link http://php.net/manual/en/arrayaccess.offsetunset.php
*
* @param mixed $offset <p> * @param mixed $offset <p>
* The offset to unset. * The offset to unset.
* </p> * </p>
*
* @return void * @return void
*/ */
public function offsetUnset($offset) public function offsetUnset($offset)

View File

@ -22,12 +22,13 @@ class PairSet
* @param string $a * @param string $a
* @param string $b * @param string $b
* @param bool $areMutuallyExclusive * @param bool $areMutuallyExclusive
*
* @return bool * @return bool
*/ */
public function has($a, $b, $areMutuallyExclusive) public function has($a, $b, $areMutuallyExclusive)
{ {
$first = $this->data[$a] ?? null; $first = $this->data[$a] ?? null;
$result = ($first && isset($first[$b])) ? $first[$b] : null; $result = $first && isset($first[$b]) ? $first[$b] : null;
if ($result === null) { if ($result === null) {
return false; return false;
} }

View File

@ -42,17 +42,19 @@ class SchemaPrinter
* *
* - commentDescriptions: * - commentDescriptions:
* Provide true to use preceding comments as the description. * Provide true to use preceding comments as the description.
* @api *
* @param bool[] $options * @param bool[] $options
*
* @api
*/ */
public static function doPrint(Schema $schema, array $options = []) : string public static function doPrint(Schema $schema, array $options = []) : string
{ {
return self::printFilteredSchema( return self::printFilteredSchema(
$schema, $schema,
function ($type) { static function ($type) {
return ! Directive::isSpecifiedDirective($type); return ! Directive::isSpecifiedDirective($type);
}, },
function ($type) { static function ($type) {
return ! Type::isBuiltInType($type); return ! Type::isBuiltInType($type);
}, },
$options $options
@ -66,7 +68,7 @@ class SchemaPrinter
{ {
$directives = array_filter( $directives = array_filter(
$schema->getDirectives(), $schema->getDirectives(),
function ($directive) use ($directiveFilter) { static function ($directive) use ($directiveFilter) {
return $directiveFilter($directive); return $directiveFilter($directive);
} }
); );
@ -83,13 +85,13 @@ class SchemaPrinter
array_merge( array_merge(
[self::printSchemaDefinition($schema)], [self::printSchemaDefinition($schema)],
array_map( array_map(
function ($directive) use ($options) { static function ($directive) use ($options) {
return self::printDirective($directive, $options); return self::printDirective($directive, $options);
}, },
$directives $directives
), ),
array_map( array_map(
function ($type) use ($options) { static function ($type) use ($options) {
return self::printType($type, $options); return self::printType($type, $options);
}, },
$types $types
@ -175,7 +177,7 @@ class SchemaPrinter
return self::printDescriptionWithComments($lines, $indentation, $firstInBlock); return self::printDescriptionWithComments($lines, $indentation, $firstInBlock);
} }
$description = ($indentation && ! $firstInBlock) $description = $indentation && ! $firstInBlock
? "\n" . $indentation . '"""' ? "\n" . $indentation . '"""'
: $indentation . '"""'; : $indentation . '"""';
@ -274,7 +276,7 @@ class SchemaPrinter
// If every arg does not have a description, print them on one line. // If every arg does not have a description, print them on one line.
if (Utils::every( if (Utils::every(
$args, $args,
function ($arg) { static function ($arg) {
return empty($arg->description); return empty($arg->description);
} }
)) { )) {
@ -286,7 +288,7 @@ class SchemaPrinter
implode( implode(
"\n", "\n",
array_map( array_map(
function ($arg, $i) use ($indentation, $options) { static function ($arg, $i) use ($indentation, $options) {
return self::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation . return self::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation .
self::printInputValue($arg); self::printInputValue($arg);
}, },
@ -358,7 +360,7 @@ class SchemaPrinter
' implements ' . implode( ' implements ' . implode(
' & ', ' & ',
array_map( array_map(
function ($i) { static function ($i) {
return $i->name; return $i->name;
}, },
$interfaces $interfaces
@ -379,7 +381,7 @@ class SchemaPrinter
return implode( return implode(
"\n", "\n",
array_map( array_map(
function ($f, $i) use ($options) { static function ($f, $i) use ($options) {
return self::printDescription($options, $f, ' ', ! $i) . ' ' . return self::printDescription($options, $f, ' ', ! $i) . ' ' .
$f->name . self::printArgs($options, $f->args, ' ') . ': ' . $f->name . self::printArgs($options, $f->args, ' ') . ': ' .
(string) $f->getType() . self::printDeprecated($f); (string) $f->getType() . self::printDeprecated($f);
@ -439,7 +441,7 @@ class SchemaPrinter
return implode( return implode(
"\n", "\n",
array_map( array_map(
function ($value, $i) use ($options) { static function ($value, $i) use ($options) {
return self::printDescription($options, $value, ' ', ! $i) . ' ' . return self::printDescription($options, $value, ' ', ! $i) . ' ' .
$value->name . self::printDeprecated($value); $value->name . self::printDeprecated($value);
}, },
@ -463,7 +465,7 @@ class SchemaPrinter
implode( implode(
"\n", "\n",
array_map( array_map(
function ($f, $i) use ($options) { static function ($f, $i) use ($options) {
return self::printDescription($options, $f, ' ', ! $i) . ' ' . self::printInputValue($f); return self::printDescription($options, $f, ' ', ! $i) . ' ' . self::printInputValue($f);
}, },
$fields, $fields,
@ -474,8 +476,9 @@ class SchemaPrinter
} }
/** /**
* @api
* @param bool[] $options * @param bool[] $options
*
* @api
*/ */
public static function printIntrospectionSchema(Schema $schema, array $options = []) : string public static function printIntrospectionSchema(Schema $schema, array $options = []) : string
{ {

View File

@ -46,6 +46,7 @@ class TypeComparators
* *
* @param AbstractType $maybeSubType * @param AbstractType $maybeSubType
* @param AbstractType $superType * @param AbstractType $superType
*
* @return bool * @return bool
*/ */
public static function isTypeSubTypeOf(Schema $schema, $maybeSubType, $superType) public static function isTypeSubTypeOf(Schema $schema, $maybeSubType, $superType)

View File

@ -64,7 +64,6 @@ class TypeInfo
private $enumValue; private $enumValue;
/** /**
*
* @param Type|null $initialType * @param Type|null $initialType
*/ */
public function __construct(Schema $schema, $initialType = null) public function __construct(Schema $schema, $initialType = null)
@ -128,6 +127,7 @@ class TypeInfo
* *
* @param Type|null $type * @param Type|null $type
* @param Type[]|null $typeMap * @param Type[]|null $typeMap
*
* @return Type[]|null * @return Type[]|null
*/ */
public static function extractTypes($type, ?array $typeMap = null) public static function extractTypes($type, ?array $typeMap = null)
@ -175,7 +175,7 @@ class TypeInfo
foreach ((array) $type->getFields() as $fieldName => $field) { foreach ((array) $type->getFields() as $fieldName => $field) {
if (! empty($field->args)) { if (! empty($field->args)) {
$fieldArgTypes = array_map( $fieldArgTypes = array_map(
function (FieldArgument $arg) { static function (FieldArgument $arg) {
return $arg->getType(); return $arg->getType();
}, },
$field->args $field->args
@ -200,6 +200,7 @@ class TypeInfo
/** /**
* @param Type[] $typeMap * @param Type[] $typeMap
*
* @return Type[] * @return Type[]
*/ */
public static function extractTypesFromDirectives(Directive $directive, array $typeMap = []) public static function extractTypesFromDirectives(Directive $directive, array $typeMap = [])
@ -304,7 +305,7 @@ class TypeInfo
if ($fieldOrDirective) { if ($fieldOrDirective) {
$argDef = Utils::find( $argDef = Utils::find(
$fieldOrDirective->args, $fieldOrDirective->args,
function ($arg) use ($node) { static function ($arg) use ($node) {
return $arg->name === $node->name->value; return $arg->name === $node->name->value;
} }
); );
@ -406,7 +407,9 @@ class TypeInfo
/** /**
* @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
*
* @return Type|null * @return Type|null
*
* @throws InvariantViolation * @throws InvariantViolation
*/ */
public static function typeFromAST(Schema $schema, $inputTypeNode) public static function typeFromAST(Schema $schema, $inputTypeNode)

View File

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace GraphQL\Utils; namespace GraphQL\Utils;
use ErrorException;
use Exception;
use GraphQL\Error\Error; use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation; use GraphQL\Error\InvariantViolation;
use GraphQL\Error\Warning; use GraphQL\Error\Warning;
@ -11,6 +13,8 @@ use GraphQL\Language\AST\Node;
use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\WrappingType; use GraphQL\Type\Definition\WrappingType;
use InvalidArgumentException; use InvalidArgumentException;
use LogicException;
use stdClass;
use Traversable; use Traversable;
use function array_keys; use function array_keys;
use function array_map; use function array_map;
@ -55,13 +59,14 @@ class Utils
{ {
static $undefined; static $undefined;
return $undefined ?: $undefined = new \stdClass(); return $undefined ?: $undefined = new stdClass();
} }
/** /**
* Check if the value is invalid * Check if the value is invalid
* *
* @param mixed $value * @param mixed $value
*
* @return bool * @return bool
*/ */
public static function isInvalid($value) public static function isInvalid($value)
@ -100,12 +105,13 @@ class Utils
/** /**
* @param mixed|Traversable $traversable * @param mixed|Traversable $traversable
*
* @return mixed|null * @return mixed|null
*/ */
public static function find($traversable, callable $predicate) public static function find($traversable, callable $predicate)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -120,13 +126,15 @@ class Utils
/** /**
* @param mixed|Traversable $traversable * @param mixed|Traversable $traversable
*
* @return mixed[] * @return mixed[]
* @throws \Exception *
* @throws Exception
*/ */
public static function filter($traversable, callable $predicate) public static function filter($traversable, callable $predicate)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -147,14 +155,16 @@ class Utils
} }
/** /**
* @param mixed|\Traversable $traversable * @param mixed|Traversable $traversable
*
* @return int[][] * @return int[][]
* @throws \Exception *
* @throws Exception
*/ */
public static function map($traversable, callable $fn) public static function map($traversable, callable $fn)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -168,19 +178,21 @@ class Utils
/** /**
* @param mixed|Traversable $traversable * @param mixed|Traversable $traversable
*
* @return mixed[] * @return mixed[]
* @throws \Exception *
* @throws Exception
*/ */
public static function mapKeyValue($traversable, callable $fn) public static function mapKeyValue($traversable, callable $fn)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
$map = []; $map = [];
foreach ($traversable as $key => $value) { foreach ($traversable as $key => $value) {
list($newKey, $newValue) = $fn($value, $key); [$newKey, $newValue] = $fn($value, $key);
$map[$newKey] = $newValue; $map[$newKey] = $newValue;
} }
@ -189,13 +201,15 @@ class Utils
/** /**
* @param mixed|Traversable $traversable * @param mixed|Traversable $traversable
*
* @return mixed[] * @return mixed[]
* @throws \Exception *
* @throws Exception
*/ */
public static function keyMap($traversable, callable $keyFn) public static function keyMap($traversable, callable $keyFn)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -215,7 +229,7 @@ class Utils
public static function each($traversable, callable $fn) public static function each($traversable, callable $fn)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -237,12 +251,13 @@ class Utils
* $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys * $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys
* *
* @param mixed[]|Traversable $traversable * @param mixed[]|Traversable $traversable
*
* @return mixed[] * @return mixed[]
*/ */
public static function groupBy($traversable, callable $keyFn) public static function groupBy($traversable, callable $keyFn)
{ {
self::invariant( self::invariant(
is_array($traversable) || $traversable instanceof \Traversable, is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable' __METHOD__ . ' expects array or Traversable'
); );
@ -259,6 +274,7 @@ class Utils
/** /**
* @param mixed[]|Traversable $traversable * @param mixed[]|Traversable $traversable
*
* @return mixed[][] * @return mixed[][]
*/ */
public static function keyValMap($traversable, callable $keyFn, callable $valFn) public static function keyValMap($traversable, callable $keyFn, callable $valFn)
@ -273,6 +289,7 @@ class Utils
/** /**
* @param mixed[] $traversable * @param mixed[] $traversable
*
* @return bool * @return bool
*/ */
public static function every($traversable, callable $predicate) public static function every($traversable, callable $predicate)
@ -305,6 +322,7 @@ class Utils
/** /**
* @param Type|mixed $var * @param Type|mixed $var
*
* @return string * @return string
*/ */
public static function getVariableType($var) public static function getVariableType($var)
@ -323,11 +341,12 @@ class Utils
/** /**
* @param mixed $var * @param mixed $var
*
* @return string * @return string
*/ */
public static function printSafeJson($var) public static function printSafeJson($var)
{ {
if ($var instanceof \stdClass) { if ($var instanceof stdClass) {
$var = (array) $var; $var = (array) $var;
} }
if (is_array($var)) { if (is_array($var)) {
@ -357,6 +376,7 @@ class Utils
/** /**
* @param Type|mixed $var * @param Type|mixed $var
*
* @return string * @return string
*/ */
public static function printSafe($var) public static function printSafe($var)
@ -401,6 +421,7 @@ class Utils
* *
* @param string $ord * @param string $ord
* @param string $encoding * @param string $encoding
*
* @return string * @return string
*/ */
public static function chr($ord, $encoding = 'UTF-8') public static function chr($ord, $encoding = 'UTF-8')
@ -420,6 +441,7 @@ class Utils
* *
* @param string $char * @param string $char
* @param string $encoding * @param string $encoding
*
* @return mixed * @return mixed
*/ */
public static function ord($char, $encoding = 'UTF-8') public static function ord($char, $encoding = 'UTF-8')
@ -442,6 +464,7 @@ class Utils
* *
* @param string $string * @param string $string
* @param int $position * @param int $position
*
* @return mixed * @return mixed
*/ */
public static function charCodeAt($string, $position) public static function charCodeAt($string, $position)
@ -453,6 +476,7 @@ class Utils
/** /**
* @param int|null $code * @param int|null $code
*
* @return string * @return string
*/ */
public static function printCharCode($code) public static function printCharCode($code)
@ -472,6 +496,7 @@ class Utils
* Upholds the spec rules about naming. * Upholds the spec rules about naming.
* *
* @param string $name * @param string $name
*
* @throws Error * @throws Error
*/ */
public static function assertValidName($name) public static function assertValidName($name)
@ -487,6 +512,7 @@ class Utils
* *
* @param string $name * @param string $name
* @param Node|null $node * @param Node|null $node
*
* @return Error|null * @return Error|null
*/ */
public static function isValidNameError($name, $node = null) public static function isValidNameError($name, $node = null)
@ -512,18 +538,19 @@ class Utils
} }
/** /**
* Wraps original closure with PHP error handling (using set_error_handler). * Wraps original callable with PHP error handling (using set_error_handler).
* Resulting closure will collect all PHP errors that occur during the call in $errors array. * Resulting callable will collect all PHP errors that occur during the call in $errors array.
* *
* @param \ErrorException[] $errors * @param ErrorException[] $errors
* @return \Closure *
* @return callable
*/ */
public static function withErrorHandling(callable $fn, array &$errors) public static function withErrorHandling(callable $fn, array &$errors)
{ {
return function () use ($fn, &$errors) { return static function () use ($fn, &$errors) {
// Catch custom errors (to report them in query results) // Catch custom errors (to report them in query results)
set_error_handler(function ($severity, $message, $file, $line) use (&$errors) { set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) {
$errors[] = new \ErrorException($message, 0, $severity, $file, $line); $errors[] = new ErrorException($message, 0, $severity, $file, $line);
}); });
try { try {
@ -536,12 +563,13 @@ class Utils
/** /**
* @param string[] $items * @param string[] $items
*
* @return string * @return string
*/ */
public static function quotedOrList(array $items) public static function quotedOrList(array $items)
{ {
$items = array_map( $items = array_map(
function ($item) { static function ($item) {
return sprintf('"%s"', $item); return sprintf('"%s"', $item);
}, },
$items $items
@ -552,12 +580,13 @@ class Utils
/** /**
* @param string[] $items * @param string[] $items
*
* @return string * @return string
*/ */
public static function orList(array $items) public static function orList(array $items)
{ {
if (count($items) === 0) { if (count($items) === 0) {
throw new \LogicException('items must not need to be empty.'); throw new LogicException('items must not need to be empty.');
} }
$selected = array_slice($items, 0, 5); $selected = array_slice($items, 0, 5);
$selectedLength = count($selected); $selectedLength = count($selected);
@ -569,7 +598,7 @@ class Utils
return array_reduce( return array_reduce(
range(1, $selectedLength - 1), range(1, $selectedLength - 1),
function ($list, $index) use ($selected, $selectedLength) { static function ($list, $index) use ($selected, $selectedLength) {
return $list . return $list .
($selectedLength > 2 ? ', ' : ' ') . ($selectedLength > 2 ? ', ' : ' ') .
($index === $selectedLength - 1 ? 'or ' : '') . ($index === $selectedLength - 1 ? 'or ' : '') .
@ -586,8 +615,10 @@ class Utils
* Includes a custom alteration from Damerau-Levenshtein to treat case changes * Includes a custom alteration from Damerau-Levenshtein to treat case changes
* as a single edit which helps identify mis-cased values with an edit distance * as a single edit which helps identify mis-cased values with an edit distance
* of 1 * of 1
*
* @param string $input * @param string $input
* @param string[] $options * @param string[] $options
*
* @return string[] * @return string[]
*/ */
public static function suggestionList($input, array $options) public static function suggestionList($input, array $options)

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace GraphQL\Utils; namespace GraphQL\Utils;
use Exception;
use GraphQL\Error\Error; use GraphQL\Error\Error;
use GraphQL\Language\AST\Node; use GraphQL\Language\AST\Node;
use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\EnumType;
@ -12,6 +13,8 @@ use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\ScalarType;
use Throwable;
use Traversable;
use function array_key_exists; use function array_key_exists;
use function array_keys; use function array_keys;
use function array_map; use function array_map;
@ -61,7 +64,7 @@ class Value
// the original error. // the original error.
try { try {
return self::ofValue($type->parseValue($value)); return self::ofValue($type->parseValue($value));
} catch (\Exception $error) { } catch (Exception $error) {
return self::ofErrors([ return self::ofErrors([
self::coercionError( self::coercionError(
sprintf('Expected type %s', $type->name), sprintf('Expected type %s', $type->name),
@ -71,7 +74,7 @@ class Value
$error $error
), ),
]); ]);
} catch (\Throwable $error) { } catch (Throwable $error) {
return self::ofErrors([ return self::ofErrors([
self::coercionError( self::coercionError(
sprintf('Expected type %s', $type->name), sprintf('Expected type %s', $type->name),
@ -95,7 +98,7 @@ class Value
$suggestions = Utils::suggestionList( $suggestions = Utils::suggestionList(
Utils::printSafe($value), Utils::printSafe($value),
array_map( array_map(
function ($enumValue) { static function ($enumValue) {
return $enumValue->name; return $enumValue->name;
}, },
$type->getValues() $type->getValues()
@ -118,7 +121,7 @@ class Value
if ($type instanceof ListOfType) { if ($type instanceof ListOfType) {
$itemType = $type->getWrappedType(); $itemType = $type->getWrappedType();
if (is_array($value) || $value instanceof \Traversable) { if (is_array($value) || $value instanceof Traversable) {
$errors = []; $errors = [];
$coercedValue = []; $coercedValue = [];
foreach ($value as $index => $itemValue) { foreach ($value as $index => $itemValue) {
@ -144,7 +147,7 @@ class Value
} }
if ($type instanceof InputObjectType) { if ($type instanceof InputObjectType) {
if (! is_object($value) && ! is_array($value) && ! $value instanceof \Traversable) { if (! is_object($value) && ! is_array($value) && ! $value instanceof Traversable) {
return self::ofErrors([ return self::ofErrors([
self::coercionError( self::coercionError(
sprintf('Expected type %s to be an object', $type->name), sprintf('Expected type %s to be an object', $type->name),
@ -229,7 +232,8 @@ class Value
* @param Node $blameNode * @param Node $blameNode
* @param mixed[]|null $path * @param mixed[]|null $path
* @param string $subMessage * @param string $subMessage
* @param \Exception|\Throwable|null $originalError * @param Exception|Throwable|null $originalError
*
* @return Error * @return Error
*/ */
private static function coercionError( private static function coercionError(
@ -258,6 +262,7 @@ class Value
* Build a string describing the path into the value where the error was found * Build a string describing the path into the value where the error was found
* *
* @param mixed[]|null $path * @param mixed[]|null $path
*
* @return string * @return string
*/ */
private static function printPath(?array $path = null) private static function printPath(?array $path = null)
@ -277,6 +282,7 @@ class Value
/** /**
* @param mixed $value * @param mixed $value
*
* @return (mixed|null)[] * @return (mixed|null)[]
*/ */
private static function ofValue($value) private static function ofValue($value)
@ -287,6 +293,7 @@ class Value
/** /**
* @param mixed|null $prev * @param mixed|null $prev
* @param mixed|null $key * @param mixed|null $key
*
* @return (mixed|null)[] * @return (mixed|null)[]
*/ */
private static function atPath($prev, $key) private static function atPath($prev, $key)
@ -297,6 +304,7 @@ class Value
/** /**
* @param Error[] $errors * @param Error[] $errors
* @param Error|Error[] $moreErrors * @param Error|Error[] $moreErrors
*
* @return Error[] * @return Error[]
*/ */
private static function add($errors, $moreErrors) private static function add($errors, $moreErrors)