Completed
Pull Request — master (#45)
by Christoffer
03:12 queued 01:10
created

NoUndefinedVariablesRule   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A enterNode() 0 11 3
B leaveNode() 0 22 5
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
46
                if (!isset($this->definedVariableNames[$variableName])) {
47
                    $operationName = $node->getName();
48
                    $this->context->reportError(
49
                        new ValidationException(
50
                            undefinedVariableMessage($variableName, $operationName ? $operationName->getValue() : null),
51
                            [$variableNode, $node]
52
                        )
53
                    );
54
                }
55
            }
56
        }
57
58
        return $node;
59
    }
60
}
61