I have custom dynamically created Enum type MyCustomEnum
witch I need to use in my ServiceProvider.
For example I call Type string now Type::string()
:
<?php
namespace App\Providers;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\ServiceProvider;
use Nuwave\Lighthouse\Schema\TypeRegistry;
use GraphQL\Type\Definition\EnumType;
class GraphQLServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @param TypeRegistry $typeRegistry
*
* @return void
*/
public function boot(TypeRegistry $typeRegistry): void
{
$typeRegistry->register(
new ObjectType([
'name' => 'MyOtherCustomType',
'fields' => function () use ($typeRegistry): array{
return [
'my_field' => Type::string()
];
},
])
);
}
}
How I can call this dynamically created type MyCustomEnum
on line 'my_field' => ...
?
CodePudding user response:
I have a php enum class named CountryEnum
which has a static method called graphEnumType()
. This method returns an array with this shape. I register it in AppServiceProvider
like this so it can be used with graphql:
$typeRegistry->register(CountryEnum::graphEnumType());
Inside the php i treat it like a php enum and call it like this:
CountryEnum::AT->value;
CodePudding user response:
Enums are not a Type, they do not get implemented like class
or struct
in any way they are true arrays, when your pass an enum, you don't actually pass the enum you pass one of the values the enum has registered to it, now this can be hidden if you don't supply values. to not be hidden when you define the enum you must supply the value for each option and then the values, therefore, have a type.
E.G
$episodeEnum = new EnumType([
'name' => 'Episode',
'description' => 'One of the films in the Star Wars Trilogy',
'values' => [
'NEWHOPE' => [
'value' => 4,
'description' => 'Released in 1977.'
],
'EMPIRE' => [
'value' => 5,
'description' => 'Released in 1980.'
],
'JEDI' => [
'value' => 6,
'description' => 'Released in 1983.'
],
]
]);
Now the enum Episode
always has a type of int
because the 3 options of the enum all have values that are ints
, so the type of that enum value is an int
. Therefore anything that uses that Episode
Enum, they have to supply what value of the enum they want to save(E.G Episode.NEWHOPE
) and that is enum value's actual value is actually what is saved (so the last E.G would actually save 4
and is there for an int), and that defines the type of what is saved/transferred, it is the type of the value.