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

UniqueDirectivesPerLocationRule   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

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

1 Method

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