From a612b780c9c08e96f969e609093e793050cfd76b Mon Sep 17 00:00:00 2001 From: vladar Date: Sat, 22 Oct 2016 17:11:03 +0700 Subject: [PATCH] Return stdClass vs empty array for empty ObjectType values (see #59) --- src/Executor/Executor.php | 8 +++- tests/Executor/ExecutorTest.php | 80 +++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/src/Executor/Executor.php b/src/Executor/Executor.php index e6236c0..14888b3 100644 --- a/src/Executor/Executor.php +++ b/src/Executor/Executor.php @@ -96,7 +96,7 @@ class Executor $data = null; } - return new ExecutionResult($data, $exeContext->errors); + return new ExecutionResult((array) $data, $exeContext->errors); } /** @@ -231,7 +231,11 @@ class Executor $results[$responseName] = $result; } } - return $results; + // see #59 + if ([] === $results) { + $results = new \stdClass(); + } + return $results; } /** diff --git a/tests/Executor/ExecutorTest.php b/tests/Executor/ExecutorTest.php index 66dc95b..6bd7c77 100644 --- a/tests/Executor/ExecutorTest.php +++ b/tests/Executor/ExecutorTest.php @@ -840,4 +840,84 @@ class ExecutorTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $result->toArray()); } + + /** + * @see https://github.com/webonyx/graphql-php/issues/59 + */ + public function testSerializesToEmptyObjectVsEmptyArray() + { + $iface = null; + + $a = new ObjectType([ + 'name' => 'A', + 'fields' => [ + 'id' => Type::id() + ], + 'interfaces' => function() use (&$iface) { + return [$iface]; + } + ]); + + $b = new ObjectType([ + 'name' => 'B', + 'fields' => [ + 'id' => Type::id() + ], + 'interfaces' => function() use (&$iface) { + return [$iface]; + } + ]); + + $iface = new InterfaceType([ + 'name' => 'Iface', + 'fields' => [ + 'id' => Type::id() + ], + 'resolveType' => function($v) use ($a, $b) { + return $v['type'] === 'A' ? $a : $b; + } + ]); + + $schema = new Schema([ + 'query' => new ObjectType([ + 'name' => 'Query', + 'fields' => [ + 'ab' => Type::listOf($iface) + ] + ]), + 'types' => [$a, $b] + ]); + + $data = [ + 'ab' => [ + ['id' => 1, 'type' => 'A'], + ['id' => 2, 'type' => 'A'], + ['id' => 3, 'type' => 'B'], + ['id' => 4, 'type' => 'B'] + ] + ]; + + $query = Parser::parse(' + { + ab { + ... on A{ + id + } + } + } + '); + + $result = Executor::execute($schema, $query, $data, null); + + $this->assertEquals([ + 'data' => [ + 'ab' => [ + ['id' => '1'], + ['id' => '2'], + new \stdClass(), + new \stdClass() + ] + ] + ], $result->toArray()); + } }