public static function isValidLiteralValue(Type $type, $valueNode)
{
// A value must be provided if the type is non-null.
if ($type instanceof NonNull) {
if (!$valueNode || $valueNode instanceof NullValueNode) {
return ['Expected "' . Utils::printSafe($type) . '", found null.'];
}
return static::isValidLiteralValue($type->getWrappedType(), $valueNode);
}
if (!$valueNode || $valueNode instanceof NullValueNode) {
return [];
}
// This function only tests literals, and assumes variables will provide
// values of the correct type.
if ($valueNode instanceof VariableNode) {
return [];
}
// Lists accept a non-list value as a list of one.
if ($type instanceof ListOfType) {
$itemType = $type->getWrappedType();
if ($valueNode instanceof ListValueNode) {
$errors = [];
foreach ($valueNode->values as $index => $itemNode) {
$tmp = static::isValidLiteralValue($itemType, $itemNode);
if ($tmp) {
$errors = array_merge($errors, Utils::map($tmp, function ($error) use($index) {
return "In element #{$index}: {$error}";
}));
}
}
return $errors;
} else {
return static::isValidLiteralValue($itemType, $valueNode);
}
}
// Input objects check each defined field and look for undefined fields.
if ($type instanceof InputObjectType) {
if ($valueNode->kind !== NodeKind::OBJECT) {
return ["Expected \"{$type->name}\", found not an object."];
}
$fields = $type->getFields();
$errors = [];
// Ensure every provided field is defined.
$fieldNodes = $valueNode->fields;
foreach ($fieldNodes as $providedFieldNode) {
if (empty($fields[$providedFieldNode->name->value])) {
$errors[] = "In field \"{$providedFieldNode->name->value}\": Unknown field.";
}
}
// Ensure every defined field is valid.
$fieldNodeMap = Utils::keyMap($fieldNodes, function ($fieldNode) {
return $fieldNode->name->value;
});
foreach ($fields as $fieldName => $field) {
$result = static::isValidLiteralValue($field->getType(), isset($fieldNodeMap[$fieldName]) ? $fieldNodeMap[$fieldName]->value : null);
if ($result) {
$errors = array_merge($errors, Utils::map($result, function ($error) use($fieldName) {
return "In field \"{$fieldName}\": {$error}";
}));
}
}
return $errors;
}
if ($type instanceof LeafType) {
// Scalar/Enum input checks to ensure the type can parse the value to
// a non-null value.
$parseResult = $type->parseLiteral($valueNode);
if (null === $parseResult) {
$printed = Printer::doPrint($valueNode);
return ["Expected type \"{$type->name}\", found {$printed}."];
}
return [];
}
throw new InvariantViolation('Must be input type');
}