graphql-php/src/Validator/Rules/KnownDirectives.php

84 lines
3.1 KiB
PHP
Raw Normal View History

2015-07-15 23:05:46 +06:00
<?php
namespace GraphQL\Validator\Rules;
use GraphQL\Error\Error;
2015-07-15 23:05:46 +06:00
use GraphQL\Language\AST\Directive;
use GraphQL\Language\AST\Field;
use GraphQL\Language\AST\FragmentDefinition;
use GraphQL\Language\AST\FragmentSpread;
use GraphQL\Language\AST\InlineFragment;
use GraphQL\Language\AST\Node;
2016-11-10 22:20:19 +00:00
use GraphQL\Language\AST\NodeType;
2015-07-15 23:05:46 +06:00
use GraphQL\Language\AST\OperationDefinition;
use GraphQL\Validator\Messages;
use GraphQL\Validator\ValidationContext;
use GraphQL\Type\Definition\Directive as DirectiveDef;
2015-07-15 23:05:46 +06:00
class KnownDirectives
{
static function unknownDirectiveMessage($directiveName)
{
return "Unknown directive \"$directiveName\".";
}
static function misplacedDirectiveMessage($directiveName, $location)
{
return "Directive \"$directiveName\" may not be used on \"$location\".";
}
2015-07-15 23:05:46 +06:00
public function __invoke(ValidationContext $context)
{
return [
2016-11-10 22:20:19 +00:00
NodeType::DIRECTIVE => function (Directive $node, $key, $parent, $path, $ancestors) use ($context) {
2015-07-15 23:05:46 +06:00
$directiveDef = null;
foreach ($context->getSchema()->getDirectives() as $def) {
if ($def->name === $node->name->value) {
$directiveDef = $def;
break;
}
}
if (!$directiveDef) {
$context->reportError(new Error(
self::unknownDirectiveMessage($node->name->value),
2015-07-15 23:05:46 +06:00
[$node]
));
return ;
2015-07-15 23:05:46 +06:00
}
$appliedTo = $ancestors[count($ancestors) - 1];
$candidateLocation = $this->getLocationForAppliedNode($appliedTo);
2015-07-15 23:05:46 +06:00
if (!$candidateLocation) {
$context->reportError(new Error(
self::misplacedDirectiveMessage($node->name->value, $node->type),
2015-07-15 23:05:46 +06:00
[$node]
));
} else if (!in_array($candidateLocation, $directiveDef->locations)) {
$context->reportError(new Error(
self::misplacedDirectiveMessage($node->name->value, $candidateLocation),
[ $node ]
));
2015-07-15 23:05:46 +06:00
}
}
];
}
private function getLocationForAppliedNode(Node $appliedTo)
{
switch ($appliedTo->kind) {
2016-11-10 22:20:19 +00:00
case NodeType::OPERATION_DEFINITION:
switch ($appliedTo->operation) {
case 'query': return DirectiveDef::LOCATION_QUERY;
case 'mutation': return DirectiveDef::LOCATION_MUTATION;
case 'subscription': return DirectiveDef::LOCATION_SUBSCRIPTION;
}
break;
2016-11-10 22:20:19 +00:00
case NodeType::FIELD: return DirectiveDef::LOCATION_FIELD;
case NodeType::FRAGMENT_SPREAD: return DirectiveDef::LOCATION_FRAGMENT_SPREAD;
case NodeType::INLINE_FRAGMENT: return DirectiveDef::LOCATION_INLINE_FRAGMENT;
case NodeType::FRAGMENT_DEFINITION: return DirectiveDef::LOCATION_FRAGMENT_DEFINITION;
}
}
2015-07-15 23:05:46 +06:00
}