Completed
Push — master ( 9c953b...e04d76 )
by Christoffer
02:37 queued 33s
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\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