Completed
Pull Request — master (#94)
by Christoffer
04:13
created

UniqueDirectivesPerLocationRule::enterNode()   B

Complexity

Conditions 5
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.439
c 0
b 0
f 0
cc 5
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\DirectiveNode;
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
        /** @var DirectiveNode[] $directives */
24
        $directives = method_exists($node, 'getDirectives') ? $node->getDirectives() : null;
25
26
        if (null !== $directives) {
0 ignored issues
show
introduced by
The condition null !== $directives is always true.
Loading history...
27
            $knownDirectives = [];
28
29
            foreach ($directives as $directive) {
30
                $directiveName = $directive->getNameValue();
31
32
                if (isset($knownDirectives[$directiveName])) {
33
                    $this->validationContext->reportError(
34
                        new ValidationException(
35
                            duplicateDirectiveMessage($directiveName),
36
                            [$knownDirectives[$directiveName], $directive]
37
                        )
38
                    );
39
                } else {
40
                    $knownDirectives[$directiveName] = $directive;
41
                }
42
            }
43
        }
44
45
        return $node;
46
    }
47
}
48