1 | <?php |
||
2 | |||
3 | namespace Digia\GraphQL\Validation\Rule; |
||
4 | |||
5 | use Digia\GraphQL\Language\Node\OperationDefinitionNode; |
||
6 | use Digia\GraphQL\Language\Node\VariableDefinitionNode; |
||
7 | use Digia\GraphQL\Language\Node\VariableNode; |
||
8 | use Digia\GraphQL\Language\Visitor\VisitorResult; |
||
9 | use Digia\GraphQL\Validation\ValidationException; |
||
10 | use function Digia\GraphQL\Validation\undefinedVariableMessage; |
||
11 | |||
12 | /** |
||
13 | * No undefined variables |
||
14 | * |
||
15 | * A GraphQL operation is only valid if all variables encountered, both directly |
||
16 | * and via fragment spreads, are defined by that operation. |
||
17 | */ |
||
18 | class NoUndefinedVariablesRule extends AbstractRule |
||
19 | { |
||
20 | /** |
||
21 | * @var array |
||
22 | */ |
||
23 | protected $definedVariableNames; |
||
24 | |||
25 | /** |
||
26 | * @inheritdoc |
||
27 | */ |
||
28 | protected function enterOperationDefinition(OperationDefinitionNode $node): VisitorResult |
||
29 | { |
||
30 | $this->definedVariableNames = []; |
||
31 | |||
32 | return new VisitorResult($node); |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * @inheritdoc |
||
37 | */ |
||
38 | protected function enterVariableDefinition(VariableDefinitionNode $node): VisitorResult |
||
39 | { |
||
40 | $this->definedVariableNames[$node->getVariable()->getNameValue()] = true; |
||
41 | |||
42 | return new VisitorResult($node); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @inheritdoc |
||
47 | */ |
||
48 | protected function leaveOperationDefinition(OperationDefinitionNode $node): VisitorResult |
||
49 | { |
||
50 | $usages = $this->context->getRecursiveVariableUsages($node); |
||
51 | |||
52 | foreach ($usages as ['node' => $variableNode]) { |
||
53 | /** @var VariableNode $variableNode */ |
||
54 | $variableName = $variableNode->getNameValue(); |
||
55 | |||
56 | if (!isset($this->definedVariableNames[$variableName])) { |
||
57 | $operationName = $node->getName(); |
||
58 | $this->context->reportError( |
||
59 | new ValidationException( |
||
60 | undefinedVariableMessage($variableName, $operationName ? $operationName->getValue() : null), |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
61 | [$variableNode, $node] |
||
62 | ) |
||
63 | ); |
||
64 | } |
||
65 | } |
||
66 | |||
67 | return new VisitorResult($node); |
||
68 | } |
||
69 | } |
||
70 |