From 48c33302a8ccaf32ca50ac27ec57abb4bb807f88 Mon Sep 17 00:00:00 2001 From: Daniel Tschinder Date: Fri, 9 Feb 2018 14:30:05 +0100 Subject: [PATCH] (Potentially Breaking) Allow serializing scalars as null. This changes the check for null/undefined to a check for undefined to determine if scalar serialization was successful or not, allowing `null` to be returned from serialize() without indicating error. This is potentially breaking for any existing custom scalar which returned `null` from `serialize()` to indicate failure. To account for this change, it should either throw an error or return `undefined`. ref: graphql/graphql-js#1104 --- src/Executor/Executor.php | 2 +- src/Type/Definition/EnumType.php | 6 +++++- src/Utils/AST.php | 14 +++++++------- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/Executor/Executor.php b/src/Executor/Executor.php index b2ba19a..c21db83 100644 --- a/src/Executor/Executor.php +++ b/src/Executor/Executor.php @@ -1187,7 +1187,7 @@ class Executor { $serializedResult = $returnType->serialize($result); - if ($serializedResult === null) { + if (Utils::isInvalid($serializedResult)) { throw new InvariantViolation( 'Expected a value of type "'. Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result) ); diff --git a/src/Type/Definition/EnumType.php b/src/Type/Definition/EnumType.php index 035c86f..1f18875 100644 --- a/src/Type/Definition/EnumType.php +++ b/src/Type/Definition/EnumType.php @@ -108,7 +108,11 @@ class EnumType extends Type implements InputType, OutputType, LeafType public function serialize($value) { $lookup = $this->getValueLookup(); - return isset($lookup[$value]) ? $lookup[$value]->name : null; + if (isset($lookup[$value])) { + return $lookup[$value]->name; + } + + return Utils::undefined(); } /** diff --git a/src/Utils/AST.php b/src/Utils/AST.php index 6fd6a9b..ea38aa4 100644 --- a/src/Utils/AST.php +++ b/src/Utils/AST.php @@ -205,15 +205,15 @@ class AST return new ObjectValueNode(['fields' => $fieldNodes]); } + Utils::invariant( + $type instanceof ScalarType || $type instanceof EnumType, + "Must provide Input Type, cannot use: " . Utils::printSafe($type) + ); + // Since value is an internally represented value, it must be serialized // to an externally represented value before converting into an AST. - if ($type instanceof LeafType) { - $serialized = $type->serialize($value); - } else { - throw new InvariantViolation("Must provide Input Type, cannot use: " . Utils::printSafe($type)); - } - - if (null === $serialized) { + $serialized = $type->serialize($value); + if (null === $serialized || Utils::isInvalid($serialized)) { return null; }