-
-
Notifications
You must be signed in to change notification settings - Fork 566
/
UniqueDirectivesPerLocation.php
96 lines (84 loc) · 3.09 KB
/
UniqueDirectivesPerLocation.php
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
93
94
95
96
<?php declare(strict_types=1);
namespace GraphQL\Validator\Rules;
use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\DirectiveDefinitionNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\Visitor;
use GraphQL\Type\Definition\Directive;
use GraphQL\Validator\QueryValidationContext;
use GraphQL\Validator\SDLValidationContext;
use GraphQL\Validator\ValidationContext;
/**
* Unique directive names per location.
*
* A GraphQL document is only valid if all non-repeatable directives at
* a given location are uniquely named.
*
* @phpstan-import-type VisitorArray from Visitor
*/
class UniqueDirectivesPerLocation extends ValidationRule
{
/** @throws InvariantViolation */
public function getVisitor(QueryValidationContext $context): array
{
return $this->getASTVisitor($context);
}
/** @throws InvariantViolation */
public function getSDLVisitor(SDLValidationContext $context): array
{
return $this->getASTVisitor($context);
}
/**
* @throws InvariantViolation
*
* @phpstan-return VisitorArray
*/
public function getASTVisitor(ValidationContext $context): array
{
/** @var array<string, true> $uniqueDirectiveMap */
$uniqueDirectiveMap = [];
$schema = $context->getSchema();
$definedDirectives = $schema !== null
? $schema->getDirectives()
: Directive::getInternalDirectives();
foreach ($definedDirectives as $directive) {
if (! $directive->isRepeatable) {
$uniqueDirectiveMap[$directive->name] = true;
}
}
$astDefinitions = $context->getDocument()->definitions;
foreach ($astDefinitions as $definition) {
if ($definition instanceof DirectiveDefinitionNode
&& ! $definition->repeatable
) {
$uniqueDirectiveMap[$definition->name->value] = true;
}
}
return [
'enter' => static function (Node $node) use ($uniqueDirectiveMap, $context): void {
if (! property_exists($node, 'directives')) {
return;
}
$knownDirectives = [];
foreach ($node->directives as $directive) {
$directiveName = $directive->name->value;
if (isset($uniqueDirectiveMap[$directiveName])) {
if (isset($knownDirectives[$directiveName])) {
$context->reportError(new Error(
static::duplicateDirectiveMessage($directiveName),
[$knownDirectives[$directiveName], $directive]
));
} else {
$knownDirectives[$directiveName] = $directive;
}
}
}
},
];
}
public static function duplicateDirectiveMessage(string $directiveName): string
{
return "The directive \"{$directiveName}\" can only be used once at this location.";
}
}