Completed
Pull Request — master (#100)
by Christoffer
03:02
created

UniqueVariableNamesRule::enterNode()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 13
nc 6
nop 1
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 function Digia\GraphQL\Validation\duplicateVariableMessage;
10
11
/**
12
 * Unique variable names
13
 *
14
 * A GraphQL operation is only valid if all its variables are uniquely named.
15
 */
16
class UniqueVariableNamesRule extends AbstractRule
17
{
18
    /**
19
     * @var string[]
20
     */
21
    protected $knownVariableNames = [];
22
23
    /**
24
     * @inheritdoc
25
     */
26
    public function enterNode(NodeInterface $node): ?NodeInterface
27
    {
28
        if ($node instanceof OperationDefinitionNode) {
29
            $this->knownVariableNames = [];
30
        }
31
32
        if ($node instanceof VariableDefinitionNode) {
33
            $variable     = $node->getVariable();
34
            $variableName = $variable->getNameValue();
35
36
            if (isset($this->knownVariableNames[$variableName])) {
37
                $this->validationContext->reportError(
38
                    new ValidationException(
39
                        duplicateVariableMessage($variableName),
40
                        [$this->knownVariableNames[$variableName], $variable->getName()]
41
                    )
42
                );
43
            } else {
44
                $this->knownVariableNames[$variableName] = $variable->getName();
45
            }
46
        }
47
48
        return $node;
49
    }
50
}
51