diff --git a/src/Type/Definition/EnumType.php b/src/Type/Definition/EnumType.php index ee47342..daf1fe0 100644 --- a/src/Type/Definition/EnumType.php +++ b/src/Type/Definition/EnumType.php @@ -44,6 +44,11 @@ class EnumType extends Type implements InputType, OutputType, LeafType if (!empty($config['values'])) { foreach ($config['values'] as $name => $value) { + + if (is_string($value) && is_int($name)) { + $value = ['name' => $value, 'value' => $value]; + } + // value will be equal to name only if 'value' is not set in definition $this->values[] = new EnumValueDefinition($value + ['name' => $name, 'value' => $name]); } diff --git a/tests/Type/EnumTypeTest.php b/tests/Type/EnumTypeTest.php index 1d637e0..e15a4ee 100644 --- a/tests/Type/EnumTypeTest.php +++ b/tests/Type/EnumTypeTest.php @@ -37,6 +37,13 @@ class EnumTypeTest extends \PHPUnit_Framework_TestCase ] ]); + $simpleEnum = new EnumType([ + 'name' => 'SimpleEnum', + 'values' => [ + 'ONE', 'TWO', 'THREE' + ] + ]); + $Complex1 = ['someRandomFunction' => function() {}]; $Complex2 = new \ArrayObject(['someRandomValue' => 123]); @@ -70,6 +77,21 @@ class EnumTypeTest extends \PHPUnit_Framework_TestCase } } ], + 'simpleEnum' => [ + 'type' => $simpleEnum, + 'args' => [ + 'fromName' => ['type' => Type::string()], + 'fromValue' => ['type' => Type::string()] + ], + 'resolve' => function($value, $args) { + if (isset($args['fromName'])) { + return $args['fromName']; + } + if (isset($args['fromValue'])) { + return $args['fromValue']; + } + } + ], 'colorInt' => [ 'type' => Type::int(), 'args' => [ @@ -413,6 +435,26 @@ class EnumTypeTest extends \PHPUnit_Framework_TestCase $this->assertArrayNotHasKey('errors', $result); } + public function testAllowsSimpleArrayAsValues() + { + $q = '{ + first: simpleEnum(fromName: "ONE") + second: simpleEnum(fromValue: "TWO") + third: simpleEnum(fromValue: "WRONG") + }'; + + $this->assertEquals( + [ + 'data' => ['first' => 'ONE', 'second' => 'TWO', 'third' => null], + 'errors' => [[ + 'message' => 'Expected a value of type "SimpleEnum" but received: WRONG', + 'locations' => [['line' => 4, 'column' => 13]] + ]] + ], + GraphQL::execute($this->schema, $q) + ); + } + private function expectFailure($query, $vars, $err) { $result = GraphQL::executeAndReturnResult($this->schema, $query, null, null, $vars);