Completed
Push — master ( 88dec8...ab51f6 )
by Christoffer
08:00 queued 05:31
created

UniqueFragmentNamesRule   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 35
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B enterNode() 0 25 4
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