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

UniqueVariableNamesRule   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 33
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B enterNode() 0 23 4
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