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\unusedVariableMessage; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* No unused variables |
14
|
|
|
* |
15
|
|
|
* A GraphQL operation is only valid if all variables defined by an operation |
16
|
|
|
* are used, either directly or within a spread fragment. |
17
|
|
|
*/ |
18
|
|
|
class NoUnusedVariablesRule extends AbstractRule |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var VariableDefinitionNode[] |
22
|
|
|
*/ |
23
|
|
|
protected $variableDefinitions; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @inheritdoc |
27
|
|
|
*/ |
28
|
|
|
protected function enterOperationDefinition(OperationDefinitionNode $node): ?NodeInterface |
29
|
|
|
{ |
30
|
|
|
$this->variableDefinitions = []; |
31
|
|
|
|
32
|
|
|
return $node; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @inheritdoc |
37
|
|
|
*/ |
38
|
|
|
protected function enterVariableDefinition(VariableDefinitionNode $node): ?NodeInterface |
39
|
|
|
{ |
40
|
|
|
$this->variableDefinitions[] = $node; |
41
|
|
|
|
42
|
|
|
return $node; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @inheritdoc |
47
|
|
|
*/ |
48
|
|
|
protected function leaveOperationDefinition(OperationDefinitionNode $node): ?NodeInterface |
49
|
|
|
{ |
50
|
|
|
$variableNamesUsed = []; |
51
|
|
|
$usages = $this->context->getRecursiveVariableUsages($node); |
52
|
|
|
$operationNameNode = $node->getName(); |
53
|
|
|
$operationName = null !== $operationNameNode ? $operationNameNode->getValue() : null; |
54
|
|
|
|
55
|
|
|
/** @var VariableNode $variableNode */ |
56
|
|
|
foreach ($usages as ['node' => $variableNode]) { |
57
|
|
|
$variableNamesUsed[$variableNode->getNameValue()] = true; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
foreach ($this->variableDefinitions as $variableDefinition) { |
61
|
|
|
$variableName = $variableDefinition->getVariable()->getNameValue(); |
62
|
|
|
|
63
|
|
|
if (!isset($variableNamesUsed[$variableName])) { |
64
|
|
|
$this->context->reportError( |
65
|
|
|
new ValidationException( |
66
|
|
|
unusedVariableMessage($variableName, $operationName), |
67
|
|
|
[$variableDefinition] |
68
|
|
|
) |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $node; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|