Completed
Push — master ( a01b08...b72ba3 )
by Vladimir
16s queued 14s
created

UniqueInputFieldNames   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
eloc 21
dl 0
loc 43
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getVisitor() 0 28 2
A duplicateInputFieldMessage() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Validator\Rules;
6
7
use GraphQL\Error\Error;
8
use GraphQL\Language\AST\NodeKind;
9
use GraphQL\Language\AST\ObjectFieldNode;
10
use GraphQL\Language\Visitor;
11
use GraphQL\Validator\ValidationContext;
12
use function array_pop;
13
use function sprintf;
14
15
class UniqueInputFieldNames extends ValidationRule
16
{
17
    /** @var string[] */
18
    public $knownNames;
19
20
    /** @var string[][] */
21
    public $knownNameStack;
22
23 172
    public function getVisitor(ValidationContext $context)
24
    {
25 172
        $this->knownNames     = [];
26 172
        $this->knownNameStack = [];
27
28
        return [
29
            NodeKind::OBJECT       => [
30
                'enter' => function () {
31 6
                    $this->knownNameStack[] = $this->knownNames;
32 6
                    $this->knownNames       = [];
33 172
                },
34
                'leave' => function () {
35 6
                    $this->knownNames = array_pop($this->knownNameStack);
36 172
                },
37
            ],
38
            NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) {
39 6
                $fieldName = $node->name->value;
40
41 6
                if (! empty($this->knownNames[$fieldName])) {
42 2
                    $context->reportError(new Error(
43 2
                        self::duplicateInputFieldMessage($fieldName),
44 2
                        [$this->knownNames[$fieldName], $node->name]
45
                    ));
46
                } else {
47 6
                    $this->knownNames[$fieldName] = $node->name;
48
                }
49
50 6
                return Visitor::skipNode();
51 172
            },
52
        ];
53
    }
54
55 2
    public static function duplicateInputFieldMessage($fieldName)
56
    {
57 2
        return sprintf('There can be only one input field named "%s".', $fieldName);
58
    }
59
}
60