forked from webonyx/graphql-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneOfInputObjectsRule.php
More file actions
92 lines (75 loc) · 3.12 KB
/
OneOfInputObjectsRule.php
File metadata and controls
92 lines (75 loc) · 3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php declare(strict_types=1);
namespace GraphQL\Validator\Rules;
use GraphQL\Error\Error;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Validator\QueryValidationContext;
/**
* OneOf Input Objects validation rule.
*
* Validates that OneOf Input Objects have exactly one non-null field provided.
*/
class OneOfInputObjectsRule extends ValidationRule
{
public function getVisitor(QueryValidationContext $context): array
{
return [
NodeKind::OBJECT => static function (ObjectValueNode $node) use ($context): void {
$type = $context->getInputType();
if ($type === null) {
return;
}
$namedType = Type::getNamedType($type);
if (! ($namedType instanceof InputObjectType) || ! $namedType->isOneOf()) {
return;
}
$providedFields = [];
$nullFields = [];
foreach ($node->fields as $fieldNode) {
$fieldName = $fieldNode->name->value;
$providedFields[] = $fieldName;
// Check if the field value is explicitly null
if ($fieldNode->value->kind === NodeKind::NULL) {
$nullFields[] = $fieldName;
}
}
$fieldCount = count($providedFields);
if ($fieldCount === 0) {
$context->reportError(new Error(
static::oneOfInputObjectExpectedExactlyOneFieldMessage($namedType->name),
[$node]
));
return;
}
if ($fieldCount > 1) {
$context->reportError(new Error(
static::oneOfInputObjectExpectedExactlyOneFieldMessage($namedType->name, $fieldCount),
[$node]
));
return;
}
// At this point, $fieldCount === 1
if (count($nullFields) > 0) {
// Exactly one field provided, but it's null
$context->reportError(new Error(
static::oneOfInputObjectFieldValueMustNotBeNullMessage($namedType->name, $nullFields[0]),
[$node]
));
}
},
];
}
public static function oneOfInputObjectExpectedExactlyOneFieldMessage(string $typeName, ?int $providedCount = null): string
{
if ($providedCount === null) {
return "OneOf input object '{$typeName}' must specify exactly one field.";
}
return "OneOf input object '{$typeName}' must specify exactly one field, but {$providedCount} fields were provided.";
}
public static function oneOfInputObjectFieldValueMustNotBeNullMessage(string $typeName, string $fieldName): string
{
return "OneOf input object '{$typeName}' field '{$fieldName}' must be non-null.";
}
}