1 | <?php |
||
2 | |||
3 | namespace Digia\GraphQL\Validation\Rule; |
||
4 | |||
5 | use Digia\GraphQL\Language\Node\NameNode; |
||
6 | use Digia\GraphQL\Language\Node\OperationDefinitionNode; |
||
7 | use Digia\GraphQL\Language\Node\VariableDefinitionNode; |
||
8 | use Digia\GraphQL\Language\Visitor\VisitorResult; |
||
9 | use Digia\GraphQL\Validation\ValidationException; |
||
10 | use function Digia\GraphQL\Validation\duplicateVariableMessage; |
||
11 | |||
12 | /** |
||
13 | * Unique variable names |
||
14 | * |
||
15 | * A GraphQL operation is only valid if all its variables are uniquely named. |
||
16 | */ |
||
17 | class UniqueVariableNamesRule extends AbstractRule |
||
18 | { |
||
19 | /** |
||
20 | * @var NameNode[] |
||
21 | */ |
||
22 | protected $knownVariableNames = []; |
||
23 | |||
24 | /** |
||
25 | * @inheritdoc |
||
26 | */ |
||
27 | protected function enterOperationDefinition(OperationDefinitionNode $node): VisitorResult |
||
28 | { |
||
29 | $this->knownVariableNames = []; |
||
30 | |||
31 | return new VisitorResult($node); |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @inheritdoc |
||
36 | */ |
||
37 | protected function enterVariableDefinition(VariableDefinitionNode $node): VisitorResult |
||
38 | { |
||
39 | $variable = $node->getVariable(); |
||
40 | $variableName = $variable->getNameValue(); |
||
41 | |||
42 | if (isset($this->knownVariableNames[$variableName])) { |
||
43 | $this->context->reportError( |
||
44 | new ValidationException( |
||
45 | duplicateVariableMessage($variableName), |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
46 | [$this->knownVariableNames[$variableName], $variable->getName()] |
||
47 | ) |
||
48 | ); |
||
49 | } else { |
||
50 | $this->knownVariableNames[$variableName] = $variable->getName(); |
||
51 | } |
||
52 | |||
53 | return new VisitorResult($node); |
||
54 | } |
||
55 | } |
||
56 |