Allow to define enum values by simply passing array of strings, e.g. 'values' => ['ONE', 'TWO', 'THREE']

This commit is contained in:
vladar 2016-10-20 19:01:30 +07:00
parent 0a79be8409
commit 09cc313072
2 changed files with 47 additions and 0 deletions

View File

@ -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]);
}

View File

@ -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);