Failed Conditions
Push — master ( a4f39b...12ee90 )
by Vladimir
11:17
created

UniqueInputFieldNames::getVisitor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 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\ASTValidationContext;
12
use GraphQL\Validator\SDLValidationContext;
13
use GraphQL\Validator\ValidationContext;
14
use function array_pop;
15
use function sprintf;
16
17
class UniqueInputFieldNames extends ValidationRule
18
{
19
    /** @var string[] */
20
    public $knownNames;
21
22
    /** @var string[][] */
23
    public $knownNameStack;
24
25 122
    public function getVisitor(ValidationContext $context)
26
    {
27 122
        return $this->getASTVisitor($context);
28
    }
29
30 207
    public function getSDLVisitor(SDLValidationContext $context)
31
    {
32 207
        return $this->getASTVisitor($context);
33
    }
34
35 322
    public function getASTVisitor(ASTValidationContext $context)
36
    {
37 322
        $this->knownNames     = [];
38 322
        $this->knownNameStack = [];
39
40
        return [
41
            NodeKind::OBJECT       => [
42
                'enter' => function () {
43 6
                    $this->knownNameStack[] = $this->knownNames;
44 6
                    $this->knownNames       = [];
45 322
                },
46
                'leave' => function () {
47 6
                    $this->knownNames = array_pop($this->knownNameStack);
48 322
                },
49
            ],
50
            NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) {
51 6
                $fieldName = $node->name->value;
52
53 6
                if (! empty($this->knownNames[$fieldName])) {
54 2
                    $context->reportError(new Error(
55 2
                        self::duplicateInputFieldMessage($fieldName),
56 2
                        [$this->knownNames[$fieldName], $node->name]
57
                    ));
58
                } else {
59 6
                    $this->knownNames[$fieldName] = $node->name;
60
                }
61
62 6
                return Visitor::skipNode();
63 322
            },
64
        ];
65
    }
66
67 2
    public static function duplicateInputFieldMessage($fieldName)
68
    {
69 2
        return sprintf('There can be only one input field named "%s".', $fieldName);
70
    }
71
}
72