-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathMyCLabsEnumType.php
More file actions
40 lines (34 loc) · 1.1 KB
/
MyCLabsEnumType.php
File metadata and controls
40 lines (34 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite\Types;
use GraphQL\Type\Definition\EnumType;
use InvalidArgumentException;
use MyCLabs\Enum\Enum;
/**
* An extension of the EnumType to support Myclabs enum.
*
* This implementation is needed to overwrite the default "serialize" method, that expects to see the exact same object
* (while there can be several instances of the same enum value with MyclabsEnum)
*/
class MyCLabsEnumType extends EnumType
{
public function __construct(string $enumClassName, string $typeName)
{
$consts = $enumClassName::toArray();
$constInstances = [];
foreach ($consts as $key => $value) {
$constInstances[$key] = ['value' => $enumClassName::$key()];
}
parent::__construct([
'name' => $typeName,
'values' => $constInstances,
]);
}
public function serialize(mixed $value): mixed
{
if (! $value instanceof Enum) {
throw new InvalidArgumentException('Expected a Myclabs Enum instance');
}
return $value->getKey();
}
}