Passed
Pull Request — master (#97)
by Christoffer
02:31
created

UniqueFragmentNamesRule::enterNode()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 13
nc 4
nop 1
1
<?php
2
3
namespace Digia\GraphQL\Validation\Rule;
4
5
use Digia\GraphQL\Error\ValidationException;
6
use Digia\GraphQL\Language\Node\FragmentDefinitionNode;
7
use Digia\GraphQL\Language\Node\NodeInterface;
8
use Digia\GraphQL\Language\Node\OperationDefinitionNode;
9
use function Digia\GraphQL\Validation\duplicateFragmentMessage;
10
11
/**
12
 * Unique fragment names
13
 *
14
 * A GraphQL document is only valid if all defined fragments have unique names.
15
 */
16
class UniqueFragmentNamesRule extends AbstractRule
17
{
18
    /**
19
     * @var string[]
20
     */
21
    protected $knownFragmentNames = [];
22
23
    /**
24
     * @inheritdoc
25
     */
26
    public function enterNode(NodeInterface $node): ?NodeInterface
27
    {
28
        if ($node instanceof OperationDefinitionNode) {
29
            // Fragments cannot be defined inside operation definitions.
30
            return null;
31
        }
32
33
        if ($node instanceof FragmentDefinitionNode) {
34
            $fragmentName = $node->getNameValue();
35
36
            if (isset($this->knownFragmentNames[$fragmentName])) {
37
                $this->validationContext->reportError(
38
                    new ValidationException(
39
                        duplicateFragmentMessage($fragmentName),
40
                        [$this->knownFragmentNames[$fragmentName], $node->getName()]
41
                    )
42
                );
43
            } else {
44
                $this->knownFragmentNames[$fragmentName] = $node->getName();
45
            }
46
47
            return null;
48
        }
49
50
        return $node;
51
    }
52
}
53