Completed
Pull Request — master (#110)
by Christoffer
03:33
created

UniqueFragmentNamesRule::enterFragmentDefinition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
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
    protected function enterOperationDefinition(OperationDefinitionNode $node): ?NodeInterface
27
    {
28
        return null; // Fragments cannot be defined inside operation definitions.
29
    }
30
31
    /**
32
     * @inheritdoc
33
     */
34
    protected function enterFragmentDefinition(FragmentDefinitionNode $node): ?NodeInterface
35
    {
36
        $fragmentName = $node->getNameValue();
37
38
        if (isset($this->knownFragmentNames[$fragmentName])) {
39
            $this->context->reportError(
40
                new ValidationException(
41
                    duplicateFragmentMessage($fragmentName),
42
                    [$this->knownFragmentNames[$fragmentName], $node->getName()]
43
                )
44
            );
45
        } else {
46
            $this->knownFragmentNames[$fragmentName] = $node->getName();
47
        }
48
49
        return null;
50
    }
51
}
52