1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Digia\GraphQL\Validation\Rule; |
4
|
|
|
|
5
|
|
|
use Digia\GraphQL\Error\GraphQLError; |
6
|
|
|
use Digia\GraphQL\Language\AST\Node\FragmentDefinitionNode; |
7
|
|
|
use Digia\GraphQL\Language\AST\Node\InlineFragmentNode; |
8
|
|
|
use Digia\GraphQL\Language\AST\Node\NodeInterface; |
9
|
|
|
use Digia\GraphQL\Type\Definition\CompositeTypeInterface; |
10
|
|
|
use function Digia\GraphQL\Util\typeFromAST; |
11
|
|
|
|
12
|
|
|
class FragmentsOnCompositeTypesRule extends AbstractRule |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @inheritdoc |
16
|
|
|
*/ |
17
|
|
|
public function enterNode( |
18
|
|
|
NodeInterface $node, |
19
|
|
|
$key = null, |
20
|
|
|
?NodeInterface $parent = null, |
21
|
|
|
array $path = [] |
22
|
|
|
): ?NodeInterface { |
23
|
|
|
if ($node instanceof InlineFragmentNode) { |
24
|
|
|
$this->validateFragementNode($node, function (NodeInterface $node) { |
25
|
|
|
/** @noinspection PhpUndefinedMethodInspection */ |
26
|
|
|
return inlineFragmentOnNonCompositeErrorMessage($node->getTypeCondition()->getNameValue()); |
|
|
|
|
27
|
|
|
}); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if ($node instanceof FragmentDefinitionNode) { |
31
|
|
|
$this->validateFragementNode($node, function (NodeInterface $node) { |
32
|
|
|
/** @noinspection PhpUndefinedMethodInspection */ |
33
|
|
|
return fragmentOnNonCompositeMessage($node->getNameValue(), $node->getTypeCondition()->getNameValue()); |
|
|
|
|
34
|
|
|
}); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $node; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param NodeInterface|InlineFragmentNode|FragmentDefinitionNode $node |
42
|
|
|
* @param callable $errorMessageFunction |
43
|
|
|
* @throws \Exception |
44
|
|
|
* @throws \TypeError |
45
|
|
|
*/ |
46
|
|
|
protected function validateFragementNode(NodeInterface $node, callable $errorMessageFunction) |
47
|
|
|
{ |
48
|
|
|
$typeCondition = $node->getTypeCondition(); |
49
|
|
|
|
50
|
|
|
if (null !== $typeCondition) { |
51
|
|
|
$type = typeFromAST($this->context->getSchema(), $typeCondition); |
52
|
|
|
|
53
|
|
|
if (null !== $type && !($type instanceof CompositeTypeInterface)) { |
54
|
|
|
$this->context->reportError(new GraphQLError($errorMessageFunction($node), [$typeCondition])); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|