Skip to content

Commit 3cc0c71

Browse files
committed
- update validation rule to keep updated with suggestions in graphql/graphql-spec#825
1 parent 982c3aa commit 3cc0c71

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/Validator/Rules/OneOfInputObjectsRule.php

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,16 @@ public function getVisitor(QueryValidationContext $context): array
3232
}
3333

3434
$providedFields = [];
35+
$nullFields = [];
36+
3537
foreach ($node->fields as $fieldNode) {
3638
$fieldName = $fieldNode->name->value;
3739
$providedFields[] = $fieldName;
40+
41+
// Check if the field value is explicitly null
42+
if ($fieldNode->value->kind === NodeKind::NULL) {
43+
$nullFields[] = $fieldName;
44+
}
3845
}
3946

4047
$fieldCount = count($providedFields);
@@ -44,11 +51,26 @@ public function getVisitor(QueryValidationContext $context): array
4451
static::oneOfInputObjectExpectedExactlyOneFieldMessage($namedType->name),
4552
[$node]
4653
));
47-
} elseif ($fieldCount > 1) {
54+
55+
return;
56+
}
57+
58+
if ($fieldCount > 1) {
4859
$context->reportError(new Error(
4960
static::oneOfInputObjectExpectedExactlyOneFieldMessage($namedType->name, $fieldCount),
5061
[$node]
5162
));
63+
64+
return;
65+
}
66+
67+
// At this point, $fieldCount === 1
68+
if (count($nullFields) > 0) {
69+
// Exactly one field provided, but it's null
70+
$context->reportError(new Error(
71+
static::oneOfInputObjectFieldValueMustNotBeNullMessage($namedType->name, $nullFields[0]),
72+
[$node]
73+
));
5274
}
5375
},
5476
];
@@ -62,4 +84,9 @@ public static function oneOfInputObjectExpectedExactlyOneFieldMessage(string $ty
6284

6385
return "OneOf input object '{$typeName}' must specify exactly one field, but {$providedCount} fields were provided.";
6486
}
87+
88+
public static function oneOfInputObjectFieldValueMustNotBeNullMessage(string $typeName, string $fieldName): string
89+
{
90+
return "OneOf input object '{$typeName}' field '{$fieldName}' must be non-null.";
91+
}
6592
}

tests/Type/OneOfInputObjectTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,13 @@ public function testOneOfInputObjectSchemaValidation(): void
124124
self::assertNotEmpty($result->errors ?? []);
125125
self::assertCount(1, $result->errors);
126126
self::assertStringContainsString('must specify exactly one field', $result->errors[0]->getMessage());
127+
128+
// Invalid query with null field value
129+
$nullQuery = '{ test(input: { stringField: null }) }';
130+
$result = GraphQL::executeQuery($schema, $nullQuery);
131+
self::assertNotEmpty($result->errors ?? []);
132+
self::assertCount(1, $result->errors);
133+
self::assertStringContainsString('must be non-null', $result->errors[0]->getMessage());
127134
}
128135

129136
public function testOneOfIntrospection(): void

0 commit comments

Comments
 (0)