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;
use ArrayAccess;
use Exception;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\BooleanValueNode;
@ -36,6 +38,9 @@ use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use stdClass;
use Throwable;
use Traversable;
use function array_combine;
use function array_key_exists;
use function array_map;
@ -77,8 +82,9 @@ class AST
*
* This is a reverse operation for AST::toArray($node)
*
* @api
* @param mixed[] $node
*
* @api
*/
public static function fromArray(array $node) : Node
{
@ -114,8 +120,9 @@ class AST
/**
* Convert AST node to serializable array
*
* @api
* @return mixed[]
*
* @api
*/
public static function toArray(Node $node)
{
@ -140,9 +147,11 @@ class AST
* | Mixed | Enum Value |
* | null | NullValue |
*
* @api
* @param Type|mixed|null $value
*
* @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode
*
* @api
*/
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.
if ($type instanceof ListOfType) {
$itemType = $type->getWrappedType();
if (is_array($value) || ($value instanceof \Traversable)) {
if (is_array($value) || ($value instanceof Traversable)) {
$valuesNodes = [];
foreach ($value as $item) {
$itemNode = self::astFromValue($item, $itemType);
@ -184,7 +193,7 @@ class AST
// in the PHP object according to the fields in the input type.
if ($type instanceof InputObjectType) {
$isArray = is_array($value);
$isArrayLike = $isArray || $value instanceof \ArrayAccess;
$isArrayLike = $isArray || $value instanceof ArrayAccess;
if ($value === null || (! $isArrayLike && ! is_object($value))) {
return null;
}
@ -204,7 +213,7 @@ class AST
} elseif ($isArray) {
$fieldExists = array_key_exists($fieldName, $value);
} elseif ($isArrayLike) {
/** @var \ArrayAccess $value */
/** @var ArrayAccess $value */
$fieldExists = $value->offsetExists($fieldName);
} else {
$fieldExists = property_exists($value, $fieldName);
@ -234,12 +243,12 @@ class AST
// to an externally represented value before converting into an AST.
try {
$serialized = $type->serialize($value);
} catch (\Exception $error) {
} catch (Exception $error) {
if ($error instanceof Error && $type instanceof EnumType) {
return null;
}
throw $error;
} catch (\Throwable $error) {
} catch (Throwable $error) {
if ($error instanceof Error && $type instanceof EnumType) {
return null;
}
@ -304,13 +313,16 @@ class AST
* | Enum Value | Mixed |
* | Null Value | null |
*
* @api
* @param ValueNode|null $valueNode
* @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();
@ -393,7 +405,7 @@ class AST
$fields = $type->getFields();
$fieldNodes = Utils::keyMap(
$valueNode->fields,
function ($field) {
static function ($field) {
return $field->name->value;
}
);
@ -442,9 +454,9 @@ class AST
// no value is returned.
try {
return $type->parseLiteral($valueNode, $variables);
} catch (\Exception $error) {
} catch (Exception $error) {
return $undefined;
} catch (\Throwable $error) {
} catch (Throwable $error) {
return $undefined;
}
}
@ -455,8 +467,10 @@ class AST
/**
* Returns true if the provided valueNode is a variable which is not defined
* in the set of variables.
*
* @param ValueNode $valueNode
* @param mixed[] $variables
*
* @return bool
*/
private static function isMissingVariable($valueNode, $variables)
@ -481,11 +495,14 @@ class AST
* | Enum | Mixed |
* | Null | null |
*
* @api
* @param Node $valueNode
* @param mixed[]|null $variables
*
* @return mixed
* @throws \Exception
*
* @throws Exception
*
* @api
*/
public static function valueFromASTUntyped($valueNode, ?array $variables = null)
{
@ -502,7 +519,7 @@ class AST
return $valueNode->value;
case $valueNode instanceof ListValueNode:
return array_map(
function ($node) use ($variables) {
static function ($node) use ($variables) {
return self::valueFromASTUntyped($node, $variables);
},
iterator_to_array($valueNode->values)
@ -510,13 +527,13 @@ class AST
case $valueNode instanceof ObjectValueNode:
return array_combine(
array_map(
function ($field) {
static function ($field) {
return $field->name->value;
},
iterator_to_array($valueNode->fields)
),
array_map(
function ($field) use ($variables) {
static function ($field) use ($variables) {
return self::valueFromASTUntyped($field->value, $variables);
},
iterator_to_array($valueNode->fields)
@ -525,7 +542,7 @@ class AST
case $valueNode instanceof VariableNode:
$variableName = $valueNode->name->value;
return ($variables && isset($variables[$variableName]))
return $variables && isset($variables[$variableName])
? $variables[$variableName]
: null;
}
@ -536,10 +553,13 @@ class AST
/**
* Returns type definition for given AST Type node
*
* @api
* @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
*
* @return Type|null
* @throws \Exception
*
* @throws Exception
*
* @api
*/
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
*
* @api
* @param string $operationName
*
* @return bool
*
* @api
*/
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\Type;
use GraphQL\Type\Definition\UnionType;
use Throwable;
use function array_reverse;
use function implode;
use function is_array;
@ -82,7 +83,7 @@ class ASTDefinitionBuilder
'description' => $this->getDescription($directiveNode),
'locations' => Utils::map(
$directiveNode->locations,
function ($node) {
static function ($node) {
return $node->value;
}
),
@ -135,7 +136,7 @@ class ASTDefinitionBuilder
{
return Utils::keyValMap(
$values,
function ($value) {
static function ($value) {
return $value->name->value;
},
function ($value) {
@ -160,6 +161,7 @@ class ASTDefinitionBuilder
/**
* @return Type|InputType
*
* @throws Error
*/
private function internalBuildWrappedType(TypeNode $typeNode)
@ -171,7 +173,9 @@ class ASTDefinitionBuilder
/**
* @param string|NamedTypeNode $ref
*
* @return Type
*
* @throws Error
*/
public function buildType($ref)
@ -186,7 +190,9 @@ class ASTDefinitionBuilder
/**
* @param string $typeName
* @param NamedTypeNode|null $typeNode
*
* @return Type
*
* @throws Error
*/
private function internalBuildType($typeName, $typeNode = null)
@ -198,7 +204,7 @@ class ASTDefinitionBuilder
$fn = $this->typeConfigDecorator;
try {
$config = $fn($type->config, $this->typeDefintionsMap[$typeName], $this->typeDefintionsMap);
} catch (\Throwable $e) {
} catch (Throwable $e) {
throw new Error(
sprintf('Type config decorator passed to %s threw an error ', static::class) .
sprintf('when building %s type: %s', $typeName, $e->getMessage()),
@ -232,7 +238,9 @@ class ASTDefinitionBuilder
/**
* @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeDefinitionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode|UnionTypeDefinitionNode $def
*
* @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType
*
* @throws Error
*/
private function makeSchemaDef($def)
@ -280,7 +288,7 @@ class ASTDefinitionBuilder
return $def->fields
? Utils::keyValMap(
$def->fields,
function ($field) {
static function ($field) {
return $field->name->value;
},
function ($field) {
@ -309,6 +317,7 @@ class ASTDefinitionBuilder
* deprecation reason.
*
* @param EnumValueDefinitionNode | FieldDefinitionNode $node
*
* @return string
*/
private function getDeprecationReason($node)
@ -357,7 +366,7 @@ class ASTDefinitionBuilder
'values' => $def->values
? Utils::keyValMap(
$def->values,
function ($enumValue) {
static function ($enumValue) {
return $enumValue->name->value;
},
function ($enumValue) {
@ -399,7 +408,7 @@ class ASTDefinitionBuilder
'name' => $def->name->value,
'description' => $this->getDescription($def),
'astNode' => $def,
'serialize' => function ($value) {
'serialize' => static function ($value) {
return $value;
},
]);
@ -422,7 +431,9 @@ class ASTDefinitionBuilder
/**
* @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeExtensionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode $def
* @param mixed[] $config
*
* @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType
*
* @throws Error
*/
private function makeSchemaDefFromConfig($def, array $config)
@ -450,6 +461,7 @@ class ASTDefinitionBuilder
/**
* @param TypeNode|ListTypeNode|NonNullTypeNode $typeNode
*
* @return TypeNode
*/
private function getNamedTypeNode(TypeNode $typeNode)
@ -464,6 +476,7 @@ class ASTDefinitionBuilder
/**
* @param TypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
*
* @return Type
*/
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\UnionType;
use GraphQL\Type\Schema;
use TypeError;
use function array_flip;
use function array_key_exists;
use function array_keys;
@ -141,7 +142,7 @@ class BreakingChangesFinder
/**
* @return string
*
* @throws \TypeError
* @throws TypeError
*/
private static function typeKindName(Type $type)
{
@ -169,7 +170,7 @@ class BreakingChangesFinder
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
*/
private static function isChangeSafeForInputObjectFieldOrFieldArg(
@ -370,8 +370,8 @@ class BreakingChangesFinder
$newType->getWrappedType()
)) ||
// moving from non-null to nullable of the same underlying type is safe
(! ($newType instanceof NonNull) &&
self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType));
! ($newType instanceof NonNull) &&
self::isChangeSafeForInputObjectFieldOrFieldArg($oldType->getWrappedType(), $newType);
}
return false;
@ -492,7 +492,7 @@ class BreakingChangesFinder
$newArgs = $newTypeFields[$fieldName]->args;
$newArgDef = Utils::find(
$newArgs,
function ($arg) use ($oldArgDef) {
static function ($arg) use ($oldArgDef) {
return $arg->name === $oldArgDef->name;
}
);
@ -531,7 +531,7 @@ class BreakingChangesFinder
$oldArgs = $oldTypeFields[$fieldName]->args;
$oldArgDef = Utils::find(
$oldArgs,
function ($arg) use ($newArgDef) {
static function ($arg) use ($newArgDef) {
return $arg->name === $newArgDef->name;
}
);
@ -586,7 +586,7 @@ class BreakingChangesFinder
foreach ($oldInterfaces as $oldInterface) {
if (Utils::find(
$newInterfaces,
function (InterfaceType $interface) use ($oldInterface) {
static function (InterfaceType $interface) use ($oldInterface) {
return $interface->name === $oldInterface->name;
}
)) {
@ -629,7 +629,7 @@ class BreakingChangesFinder
{
return Utils::keyMap(
$schema->getDirectives(),
function ($dir) {
static function ($dir) {
return $dir->name;
}
);
@ -678,7 +678,7 @@ class BreakingChangesFinder
{
return Utils::keyMap(
$directive->args ?: [],
function ($arg) {
static function ($arg) {
return $arg->name;
}
);
@ -831,7 +831,6 @@ class BreakingChangesFinder
}
/**
*
* @return string[][]
*/
public static function findInterfacesAddedToObjectTypes(
@ -853,7 +852,7 @@ class BreakingChangesFinder
foreach ($newInterfaces as $newInterface) {
if (Utils::find(
$oldInterfaces,
function (InterfaceType $interface) use ($newInterface) {
static function (InterfaceType $interface) use ($newInterface) {
return $interface->name === $newInterface->name;
}
)) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace GraphQL\Utils;
use ErrorException;
use Exception;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Error\Warning;
@ -11,6 +13,8 @@ use GraphQL\Language\AST\Node;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\WrappingType;
use InvalidArgumentException;
use LogicException;
use stdClass;
use Traversable;
use function array_keys;
use function array_map;
@ -55,13 +59,14 @@ class Utils
{
static $undefined;
return $undefined ?: $undefined = new \stdClass();
return $undefined ?: $undefined = new stdClass();
}
/**
* Check if the value is invalid
*
* @param mixed $value
*
* @return bool
*/
public static function isInvalid($value)
@ -100,12 +105,13 @@ class Utils
/**
* @param mixed|Traversable $traversable
*
* @return mixed|null
*/
public static function find($traversable, callable $predicate)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
@ -120,13 +126,15 @@ class Utils
/**
* @param mixed|Traversable $traversable
*
* @return mixed[]
* @throws \Exception
*
* @throws Exception
*/
public static function filter($traversable, callable $predicate)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
@ -147,14 +155,16 @@ class Utils
}
/**
* @param mixed|\Traversable $traversable
* @param mixed|Traversable $traversable
*
* @return int[][]
* @throws \Exception
*
* @throws Exception
*/
public static function map($traversable, callable $fn)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
@ -168,20 +178,22 @@ class Utils
/**
* @param mixed|Traversable $traversable
*
* @return mixed[]
* @throws \Exception
*
* @throws Exception
*/
public static function mapKeyValue($traversable, callable $fn)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
$map = [];
foreach ($traversable as $key => $value) {
list($newKey, $newValue) = $fn($value, $key);
$map[$newKey] = $newValue;
[$newKey, $newValue] = $fn($value, $key);
$map[$newKey] = $newValue;
}
return $map;
@ -189,13 +201,15 @@ class Utils
/**
* @param mixed|Traversable $traversable
*
* @return mixed[]
* @throws \Exception
*
* @throws Exception
*/
public static function keyMap($traversable, callable $keyFn)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
@ -215,7 +229,7 @@ class Utils
public static function each($traversable, callable $fn)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof 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
*
* @param mixed[]|Traversable $traversable
*
* @return mixed[]
*/
public static function groupBy($traversable, callable $keyFn)
{
self::invariant(
is_array($traversable) || $traversable instanceof \Traversable,
is_array($traversable) || $traversable instanceof Traversable,
__METHOD__ . ' expects array or Traversable'
);
@ -259,6 +274,7 @@ class Utils
/**
* @param mixed[]|Traversable $traversable
*
* @return mixed[][]
*/
public static function keyValMap($traversable, callable $keyFn, callable $valFn)
@ -273,6 +289,7 @@ class Utils
/**
* @param mixed[] $traversable
*
* @return bool
*/
public static function every($traversable, callable $predicate)
@ -305,6 +322,7 @@ class Utils
/**
* @param Type|mixed $var
*
* @return string
*/
public static function getVariableType($var)
@ -323,11 +341,12 @@ class Utils
/**
* @param mixed $var
*
* @return string
*/
public static function printSafeJson($var)
{
if ($var instanceof \stdClass) {
if ($var instanceof stdClass) {
$var = (array) $var;
}
if (is_array($var)) {
@ -357,6 +376,7 @@ class Utils
/**
* @param Type|mixed $var
*
* @return string
*/
public static function printSafe($var)
@ -401,6 +421,7 @@ class Utils
*
* @param string $ord
* @param string $encoding
*
* @return string
*/
public static function chr($ord, $encoding = 'UTF-8')
@ -420,6 +441,7 @@ class Utils
*
* @param string $char
* @param string $encoding
*
* @return mixed
*/
public static function ord($char, $encoding = 'UTF-8')
@ -442,6 +464,7 @@ class Utils
*
* @param string $string
* @param int $position
*
* @return mixed
*/
public static function charCodeAt($string, $position)
@ -453,6 +476,7 @@ class Utils
/**
* @param int|null $code
*
* @return string
*/
public static function printCharCode($code)
@ -472,6 +496,7 @@ class Utils
* Upholds the spec rules about naming.
*
* @param string $name
*
* @throws Error
*/
public static function assertValidName($name)
@ -487,6 +512,7 @@ class Utils
*
* @param string $name
* @param Node|null $node
*
* @return Error|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).
* Resulting closure will collect all PHP errors that occur during the call in $errors array.
* Wraps original callable with PHP error handling (using set_error_handler).
* Resulting callable will collect all PHP errors that occur during the call in $errors array.
*
* @param \ErrorException[] $errors
* @return \Closure
* @param ErrorException[] $errors
*
* @return callable
*/
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)
set_error_handler(function ($severity, $message, $file, $line) use (&$errors) {
$errors[] = new \ErrorException($message, 0, $severity, $file, $line);
set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) {
$errors[] = new ErrorException($message, 0, $severity, $file, $line);
});
try {
@ -536,12 +563,13 @@ class Utils
/**
* @param string[] $items
*
* @return string
*/
public static function quotedOrList(array $items)
{
$items = array_map(
function ($item) {
static function ($item) {
return sprintf('"%s"', $item);
},
$items
@ -552,12 +580,13 @@ class Utils
/**
* @param string[] $items
*
* @return string
*/
public static function orList(array $items)
{
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);
$selectedLength = count($selected);
@ -569,7 +598,7 @@ class Utils
return array_reduce(
range(1, $selectedLength - 1),
function ($list, $index) use ($selected, $selectedLength) {
static function ($list, $index) use ($selected, $selectedLength) {
return $list .
($selectedLength > 2 ? ', ' : ' ') .
($index === $selectedLength - 1 ? 'or ' : '') .
@ -586,8 +615,10 @@ class Utils
* 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
* of 1
*
* @param string $input
* @param string[] $options
*
* @return string[]
*/
public static function suggestionList($input, array $options)

View File

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