Repository navigation
Description
Location (webonyx/graphql-php @ 936133b):
src/Utils/Value.php:113-121: the input object branch ofValue::coerceInputValue()accepts any PHP array, including lists.src/Utils/Value.php:143-148andsrc/Utils/Value.php:152-170: the list is then checked as if it were an object, which reports missing required fields and treats each index as an unknown field.
if ($value instanceof \stdClass) {
// Cast objects to associative array before checking the fields.
// Note that the coerced value will be an array.
$value = (array) $value;
} elseif (! is_array($value)) {
return self::ofErrors([
CoercionError::make("Expected type \"{$type->name}\" to be an object.", $path, $value),
]);
}Problem
When a client sends a JSON array where an input object is expected, the type mismatch is never reported directly. Instead, the error list says that required fields were not provided and that fields named "0", "1", and so on do not exist, with one error per list item. The client never sent fields with those names.
This only affects diagnostics. The value is rejected either way, except for an empty array. An empty array has to stay accepted, because json_decode() with associative arrays turns {} into [], and PHP can't tell the two apart.
The current wording for a single-item list is pinned by tests/Regression/Issue467Test.php:39. That test guards the fix for the crash in #467, where the reporter suggested this message, so changing the wording means updating the test.
Reproduction
Script
use GraphQL\GraphQL;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
$input = new InputObjectType([
'name' => 'TestInput',
'fields' => [
'foo' => Type::nonNull(Type::int()),
'bar' => Type::int(),
],
]);
$schema = new Schema(['query' => new ObjectType([
'name' => 'Query',
'fields' => [
'field' => [
'type' => Type::string(),
'args' => ['input' => $input],
],
],
])]);
$result = GraphQL::executeQuery(
$schema,
'query ($input: TestInput) { field(input: $input) }',
null,
null,
['input' => [1, 2, 3]],
);
foreach ($result->errors as $error) {
echo $error->getMessage(), "\n";
}Variable "$input" got invalid value [1,2,3]; Field "foo" of required type "Int!" was not provided.
Variable "$input" got invalid value [1,2,3]; Field "0" is not defined by type "TestInput".
Variable "$input" got invalid value [1,2,3]; Field "1" is not defined by type "TestInput".
Variable "$input" got invalid value [1,2,3]; Field "2" is not defined by type "TestInput".
Regression tests for tests/Utils/CoerceInputValueTest.php, plus the updated message in Issue467Test:
Test patch
diff --git a/tests/Regression/Issue467Test.php b/tests/Regression/Issue467Test.php
--- a/tests/Regression/Issue467Test.php
+++ b/tests/Regression/Issue467Test.php
@@ -36,7 +36,7 @@ query echo ($msg: MsgInput) {
$schema = BuildSchema::build($schemaStr);
$result = GraphQL::executeQuery($schema, $query, null, null, $variables);
- $expectedError = 'Variable "$msg" got invalid value ["my message"]; Field "0" is not defined by type "MsgInput".';
+ $expectedError = 'Variable "$msg" got invalid value ["my message"]; Expected type "MsgInput" to be an object.';
self::assertCount(1, $result->errors);
self::assertSame($expectedError, $result->errors[0]->getMessage());
}
diff --git a/tests/Utils/CoerceInputValueTest.php b/tests/Utils/CoerceInputValueTest.php
--- a/tests/Utils/CoerceInputValueTest.php
+++ b/tests/Utils/CoerceInputValueTest.php
@@ -391,6 +391,38 @@ final class CoerceInputValueTest extends TestCase
)]);
}
+ /** @see it('returns an error for an array type', () => { */
+ public function testReturnsAnErrorForAnArrayType(): void
+ {
+ $result = Value::coerceInputValue([['foo' => 1], ['bar' => 1]], $this->testInputObject);
+ $this->expectGraphQLError($result, [CoercionError::make(
+ 'Expected type "TestInputObject" to be an object.',
+ null,
+ [['foo' => 1], ['bar' => 1]]
+ )]);
+ }
+
+ /** @see it('returns an error for an array type on a nested field', () => { */
+ public function testReturnsAnErrorForAnArrayTypeOnANestedField(): void
+ {
+ $result = Value::coerceInputValue(['foo' => 1, 'nested' => [1, 2, 3]], $this->testInputObject);
+ $this->expectGraphQLError($result, [CoercionError::make(
+ 'Expected type "TestInputObject" to be an object.',
+ ['nested'],
+ [1, 2, 3]
+ )]);
+ }
+
+ public function testTreatsAnEmptyArrayAsAnEmptyObject(): void
+ {
+ $result = Value::coerceInputValue([], $this->testInputObject);
+ $this->expectGraphQLError($result, [CoercionError::make(
+ 'Field "foo" of required type "Int!" was not provided.',
+ null,
+ []
+ )]);
+ }
+
/** @see it('returns an error for an invalid field', () => { */
public function testReturnsAnErrorForAnInvalidField(): void
{There were 2 failures:
1) GraphQL\Tests\Utils\CoerceInputValueTest::testReturnsAnErrorForAnArrayType
Failed asserting that actual size 3 matches expected size 1.
tests/Utils/CoerceInputValueTest.php:680
tests/Utils/CoerceInputValueTest.php:398
2) GraphQL\Tests\Utils\CoerceInputValueTest::testReturnsAnErrorForAnArrayTypeOnANestedField
Failed asserting that actual size 4 matches expected size 1.
tests/Utils/CoerceInputValueTest.php:680
tests/Utils/CoerceInputValueTest.php:409
FAILURES!
Tests: 3, Assertions: 13, Failures: 2.
Environment:
- Commit:
936133ba405b62ca0d0be2a7b5fca917defa4519(master) - Toolchain: PHP 8.4.27, PHPUnit 10.5.66
Already fixed in graphql/graphql-js
PR: graphql/graphql-js#4367, "fix(coerce-input-value): input object coercion rejects arrays" (merged 2025-04-05, merge commit 5adeb7f). It rejects arrays with the existing "to be an object" error, at the top level and on nested fields. graphql-js is another implementation of the same spec, so this is precedent rather than an obligation.
How graphql-js fixed it (relevant hunks, verbatim):
--- a/src/utilities/coerceInputValue.ts
+++ b/src/utilities/coerceInputValue.ts
@@ -86,7 +86,7 @@ function coerceInputValueImpl(
}
if (isInputObjectType(type)) {
- if (!isObjectLike(inputValue)) {
+ if (!isObjectLike(inputValue) || Array.isArray(inputValue)) {
onError(
pathToArray(path),
inputValue,Suggested fix
Reuse the existing error for arrays whose first key is 0. No input field can be named 0, so these values could never coerce anyway; the check runs in constant time, works on PHP 7.4, and leaves empty arrays and stdClass input alone:
diff --git a/src/Utils/Value.php b/src/Utils/Value.php
--- a/src/Utils/Value.php
+++ b/src/Utils/Value.php
@@ -114,7 +114,9 @@ class Value
// Cast objects to associative array before checking the fields.
// Note that the coerced value will be an array.
$value = (array) $value;
- } elseif (! is_array($value)) {
+ } elseif (! is_array($value) || array_key_first($value) === 0) {
+ // A list is not an object. An empty array stays accepted, since it is how
+ // json_decode() with associative arrays represents an empty object.
return self::ofErrors([
CoercionError::make("Expected type \"{$type->name}\" to be an object.", $path, $value),
]);Verified on 936133b (PHP 8.4.27, PHPUnit 10.5.66): the two list tests and the updated Issue467Test fail without this patch and pass with it; no other test results change. testTreatsAnEmptyArrayAsAnEmptyObject passes both ways. With the patch, the script above prints a single error:
Variable "$input" got invalid value [1,2,3]; Expected type "TestInput" to be an object.
I can submit a PR for this.
Checked issues and PRs for list values on input objects and this error message: #467 fixed the crash that pinned the current wording, and #1195 and #1891 are about coercion error paths and @oneOf. None proposes rejecting lists directly.
Activity