Completed
Pull Request — master (#66)
by Christoffer
02:18
created

NoUndefinedVariablesRule::enterNode()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
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
    public function enterNode(NodeInterface $node): ?NodeInterface
29
    {
30
        if ($node instanceof OperationDefinitionNode) {
31
            $this->definedVariableNames = [];
32
        }
33
34
        if ($node instanceof VariableDefinitionNode) {
35
            $this->definedVariableNames[$node->getVariable()->getNameValue()] = true;
36
        }
37
38
        return $node;
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public function leaveNode(NodeInterface $node): ?NodeInterface
45
    {
46
        if ($node instanceof OperationDefinitionNode) {
47
            $usages = $this->validationContext->getRecursiveVariableUsages($node);
48
49
            foreach ($usages as ['node' => $variableNode]) {
50
                /** @var VariableNode $variableNode */
51
                $variableName = $variableNode->getNameValue();
52
53
                if (!isset($this->definedVariableNames[$variableName])) {
54
                    $operationName = $node->getName();
55
                    $this->validationContext->reportError(
56
                        new ValidationException(
57
                            undefinedVariableMessage($variableName, $operationName ? $operationName->getValue() : null),
58
                            [$variableNode, $node]
59
                        )
60
                    );
61
                }
62
            }
63
        }
64
65
        return $node;
66
    }
67
}
68