Passed
Pull Request — master (#94)
by Christoffer
02:32
created

UniqueDirectivesPerLocationRule::enterNode()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 13
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\DirectivesInterface;
7
use Digia\GraphQL\Language\Node\NodeInterface;
8
use function Digia\GraphQL\Validation\duplicateDirectiveMessage;
9
10
/**
11
 * Unique directive names per location
12
 *
13
 * A GraphQL document is only valid if all directives at a given location
14
 * are uniquely named.
15
 */
16
class UniqueDirectivesPerLocationRule extends AbstractRule
17
{
18
    /**
19
     * @inheritdoc
20
     */
21
    public function enterNode(NodeInterface $node): ?NodeInterface
22
    {
23
        if ($node instanceof DirectivesInterface) {
24
            $directives      = $node->getDirectives();
25
            $knownDirectives = [];
26
27
            foreach ($directives as $directive) {
28
                $directiveName = $directive->getNameValue();
29
30
                if (isset($knownDirectives[$directiveName])) {
31
                    $this->validationContext->reportError(
32
                        new ValidationException(
33
                            duplicateDirectiveMessage($directiveName),
34
                            [$knownDirectives[$directiveName], $directive]
35
                        )
36
                    );
37
                } else {
38
                    $knownDirectives[$directiveName] = $directive;
39
                }
40
            }
41
        }
42
43
        return $node;
44
    }
45
}
46