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

UniqueInputFieldNames::getVisitor()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 28
ccs 15
cts 15
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 2
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