resolveType for interface/unions is now allowed to return type name vs instance

This commit is contained in:
vladar 2016-10-18 22:23:20 +07:00
parent 89eb6dede9
commit 3e2d9459aa
2 changed files with 84 additions and 2 deletions

View File

@ -734,6 +734,11 @@ class Executor
call_user_func($resolveType, $result, $exeContext->contextValue, $info) :
Type::getTypeOf($result, $exeContext->contextValue, $info, $returnType);
// If resolveType returns a string, we assume it's a ObjectType name.
if (is_string($runtimeType)) {
$runtimeType = $exeContext->schema->getType($runtimeType);
}
if (!($runtimeType instanceof ObjectType)) {
throw new Error(
"Abstract type {$returnType} must resolve to an Object type at runtime " .

View File

@ -1,6 +1,8 @@
<?php
namespace GraphQL\Tests\Executor;
require_once __DIR__ . '/TestClasses.php';
use GraphQL\Executor\ExecutionResult;
use GraphQL\Executor\Executor;
use GraphQL\FormattedError;
@ -13,8 +15,6 @@ use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
spl_autoload_call('GraphQL\Tests\Executor\TestClasses');
class AbstractTest extends \PHPUnit_Framework_TestCase
{
// Execute: Handles execution of abstract types
@ -358,4 +358,81 @@ class AbstractTest extends \PHPUnit_Framework_TestCase
];
$this->assertEquals($expected, $result);
}
/**
* @it resolveType allows resolving with type name
*/
public function testResolveTypeAllowsResolvingWithTypeName()
{
$PetType = new InterfaceType([
'name' => 'Pet',
'resolveType' => function($obj) {
if ($obj instanceof Dog) return 'Dog';
if ($obj instanceof Cat) return 'Cat';
return null;
},
'fields' => [
'name' => [ 'type' => Type::string() ]
]
]);
$DogType = new ObjectType([
'name' => 'Dog',
'interfaces' => [ $PetType ],
'fields' => [
'name' => [ 'type' => Type::string() ],
'woofs' => [ 'type' => Type::boolean() ],
]
]);
$CatType = new ObjectType([
'name' => 'Cat',
'interfaces' => [ $PetType ],
'fields' => [
'name' => [ 'type' => Type::string() ],
'meows' => [ 'type' => Type::boolean() ],
]
]);
$schema = new Schema([
'query' => new ObjectType([
'name' => 'Query',
'fields' => [
'pets' => [
'type' => Type::listOf($PetType),
'resolve' => function() {
return [
new Dog('Odie', true),
new Cat('Garfield', false)
];
}
]
]
]),
'types' => [ $CatType, $DogType ]
]);
$query = '{
pets {
name
... on Dog {
woofs
}
... on Cat {
meows
}
}
}';
$result = GraphQL::execute($schema, $query);
$this->assertEquals([
'data' => [
'pets' => [
['name' => 'Odie', 'woofs' => true],
['name' => 'Garfield', 'meows' => false]
]
]
], $result);
}
}