|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace GraphQL\Validator\Rules; |
|
6
|
|
|
|
|
7
|
|
|
use GraphQL\Error\Error; |
|
8
|
|
|
use GraphQL\Language\AST\FragmentDefinitionNode; |
|
9
|
|
|
use GraphQL\Language\AST\NodeKind; |
|
10
|
|
|
use GraphQL\Language\AST\SelectionSetNode; |
|
11
|
|
|
use GraphQL\Language\AST\VariableDefinitionNode; |
|
12
|
|
|
use GraphQL\Language\Visitor; |
|
13
|
|
|
use GraphQL\Type\Definition\NonNull; |
|
14
|
|
|
use GraphQL\Validator\ValidationContext; |
|
15
|
|
|
use function sprintf; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Variable's default value is allowed |
|
19
|
|
|
* |
|
20
|
|
|
* A GraphQL document is only valid if all variable default values are allowed |
|
21
|
|
|
* due to a variable not being required. |
|
22
|
|
|
*/ |
|
23
|
|
|
class VariablesDefaultValueAllowed extends ValidationRule |
|
24
|
|
|
{ |
|
25
|
120 |
|
public function getVisitor(ValidationContext $context) |
|
26
|
|
|
{ |
|
27
|
|
|
return [ |
|
28
|
|
|
NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $node) use ($context) { |
|
29
|
18 |
|
$name = $node->variable->name->value; |
|
30
|
18 |
|
$defaultValue = $node->defaultValue; |
|
31
|
18 |
|
$type = $context->getInputType(); |
|
32
|
18 |
|
if ($type instanceof NonNull && $defaultValue) { |
|
33
|
2 |
|
$context->reportError( |
|
34
|
2 |
|
new Error( |
|
35
|
2 |
|
self::defaultForRequiredVarMessage( |
|
36
|
2 |
|
$name, |
|
37
|
2 |
|
$type, |
|
38
|
2 |
|
$type->getWrappedType() |
|
39
|
|
|
), |
|
40
|
2 |
|
[$defaultValue] |
|
41
|
|
|
) |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
18 |
|
return Visitor::skipNode(); |
|
46
|
120 |
|
}, |
|
47
|
|
|
NodeKind::SELECTION_SET => static function (SelectionSetNode $node) { |
|
|
|
|
|
|
48
|
119 |
|
return Visitor::skipNode(); |
|
49
|
120 |
|
}, |
|
50
|
|
|
NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) { |
|
|
|
|
|
|
51
|
11 |
|
return Visitor::skipNode(); |
|
52
|
120 |
|
}, |
|
53
|
|
|
]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
public static function defaultForRequiredVarMessage($varName, $type, $guessType) |
|
57
|
|
|
{ |
|
58
|
2 |
|
return sprintf( |
|
59
|
2 |
|
'Variable "$%s" of type "%s" is required and will not use the default value. Perhaps you meant to use type "%s".', |
|
60
|
2 |
|
$varName, |
|
61
|
2 |
|
$type, |
|
62
|
2 |
|
$guessType |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.