Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix exception when no args declared #246

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Execution/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ public function __construct($data = [], $variables = [])
if (!array_key_exists($ref->getName(), $variables)) {
/** @var Variable $variable */
$variable = $ref->getVariable();
/**
* If $variable is null, then it was not declared in the operation arguments
* @see https://graphql.org/learn/queries/#variables
*/
if (is_null($variable)) {
throw new InvalidRequestException(sprintf("Variable %s hasn't been declared", $ref->getName()), $ref->getLocation());
}
if ($variable->hasDefaultValue()) {
$variables[$variable->getName()] = $variable->getDefaultValue()->getValue();
continue;
Expand Down
57 changes: 57 additions & 0 deletions tests/Issues/Issue238/Issue238Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Youshido\Tests\Issue238;

use PHPUnit\Framework\TestCase;
use Youshido\GraphQL\Schema\Schema;
use Youshido\GraphQL\Execution\Processor;
use Youshido\GraphQL\Type\Scalar\IntType;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Type\Object\ObjectType;
use Youshido\GraphQL\Type\Scalar\StringType;

class Issue238Test extends TestCase
{
public function testNotDefinedVariableThrowsException()
{
$schema = new Schema([
'query' => new ObjectType([
'name' => 'RootQuery',
'fields' => [
'currentUser' => [
'type' => new StringType(),
'args' => [
'age' => [
'type' => new IntType(),
'defaultValue' => 20,
],
],
'resolve' => static function ($source, $args, ResolveInfo $info) {
return 'Alex age ' . $args['age'];
},
],
],
]),
]);

$processor = new Processor($schema);

/**
* If using a variable in a query, it must be defined in the operation
* $properQuery = 'query GetUserAge($age:Int) { currentUser(age:$age) }';
* When not declaring the variable in the operation, it must return a nice error message
* (instead of throwing a RuntimeException)
*/
$unproperQuery = '{ currentUser(age:$age) }';
$response = $processor->processPayload($unproperQuery)->getResponseData();
if ($this->assertArrayHasKey(
'errors',
$response
)) {
$this->assertArraySubset(
['message' => 'Variable age hasn\'t been declared'],
$response['errors']
);
}
}
}