Completed
Push — master ( 974258...005b1a )
by Vladimir
19:57 queued 16:19
created

UniqueInputFieldNames::getVisitor()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.1852

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 28
ccs 5
cts 15
cp 0.3333
rs 9.6666
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 3.1852
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 127
    public function getVisitor(ValidationContext $context)
24
    {
25 127
        $this->knownNames     = [];
26 127
        $this->knownNameStack = [];
27
28
        return [
29
            NodeKind::OBJECT       => [
30
                'enter' => function () {
31
                    $this->knownNameStack[] = $this->knownNames;
32
                    $this->knownNames       = [];
33 127
                },
34
                'leave' => function () {
35
                    $this->knownNames = array_pop($this->knownNameStack);
36 127
                },
37
            ],
38
            NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) {
39
                $fieldName = $node->name->value;
40
41
                if (! empty($this->knownNames[$fieldName])) {
42
                    $context->reportError(new Error(
43
                        self::duplicateInputFieldMessage($fieldName),
44
                        [$this->knownNames[$fieldName], $node->name]
45
                    ));
46
                } else {
47
                    $this->knownNames[$fieldName] = $node->name;
48
                }
49
50
                return Visitor::skipNode();
51 127
            },
52
        ];
53
    }
54
55
    public static function duplicateInputFieldMessage($fieldName)
56
    {
57
        return sprintf('There can be only one input field named "%s".', $fieldName);
58
    }
59
}
60