|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Digia\GraphQL\Validation\Rule; |
|
4
|
|
|
|
|
5
|
|
|
use Digia\GraphQL\Error\ValidationException; |
|
6
|
|
|
use Digia\GraphQL\Language\Node\NodeInterface; |
|
7
|
|
|
use Digia\GraphQL\Language\Node\OperationDefinitionNode; |
|
8
|
|
|
use Digia\GraphQL\Language\Node\VariableDefinitionNode; |
|
9
|
|
|
use Digia\GraphQL\Language\Node\VariableNode; |
|
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): ?NodeInterface |
|
29
|
|
|
{ |
|
30
|
|
|
$this->definedVariableNames = []; |
|
31
|
|
|
|
|
32
|
|
|
return $node; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @inheritdoc |
|
37
|
|
|
*/ |
|
38
|
|
|
protected function enterVariableDefinition(VariableDefinitionNode $node): ?NodeInterface |
|
39
|
|
|
{ |
|
40
|
|
|
$this->definedVariableNames[$node->getVariable()->getNameValue()] = true; |
|
41
|
|
|
|
|
42
|
|
|
return $node; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @inheritdoc |
|
47
|
|
|
*/ |
|
48
|
|
|
protected function leaveOperationDefinition(OperationDefinitionNode $node): ?NodeInterface |
|
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), |
|
61
|
|
|
[$variableNode, $node] |
|
62
|
|
|
) |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return $node; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|