Completed
Pull Request — master (#45)
by Christoffer
02:09
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\AST\Node\NodeInterface;
7
use Digia\GraphQL\Language\AST\Node\OperationDefinitionNode;
8
use Digia\GraphQL\Language\AST\Node\VariableDefinitionNode;
9
use Digia\GraphQL\Language\AST\Node\VariableNode;
10
11
class NoUndefinedVariablesRule extends AbstractRule
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $definedVariableNames;
17
18
    /**
19
     * @inheritdoc
20
     */
21
    public function enterNode(NodeInterface $node): ?NodeInterface
22
    {
23
        if ($node instanceof OperationDefinitionNode) {
24
            $this->definedVariableNames = [];
25
        }
26
27
        if ($node instanceof VariableDefinitionNode) {
28
            $this->definedVariableNames[$node->getVariable()->getNameValue()] = true;
29
        }
30
31
        return $node;
32
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public function leaveNode(NodeInterface $node): ?NodeInterface
38
    {
39
        if ($node instanceof OperationDefinitionNode) {
40
            $usages = $this->context->getVariableUsages($node);
41
42
            foreach ($usages as ['node' => $variableNode]) {
43
                /** @var VariableNode $variableNode */
44
                $variableName = $variableNode->getNameValue();
45
                if (!isset($this->definedVariableNames[$variableName])) {
46
                    $operationName = $node->getName();
47
                    $this->context->reportError(
48
                        new ValidationException(
49
                            undefinedVariableMessage($variableName, $operationName ? $operationName->getValue() : null),
50
                            [$variableNode, $node]
51
                        )
52
                    );
53
                }
54
            }
55
        }
56
57
        return $node;
58
    }
59
}
60