1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of laravel.su package. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace App\GraphQL\Feature\Enum; |
11
|
|
|
|
12
|
|
|
use GraphQL\Type\Definition\EnumType; |
13
|
|
|
use CommerceGuys\Enum\AbstractEnum as BaseEnum; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class EnumTransfer |
17
|
|
|
* @package App\GraphQL\Feature\Enum |
18
|
|
|
*/ |
19
|
|
|
class EnumTransfer |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array|EnumType[] |
23
|
|
|
*/ |
24
|
|
|
private $enums = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param BaseEnum|string $enum |
28
|
|
|
* @param string $shortName |
29
|
|
|
* |
30
|
|
|
* @return array |
31
|
|
|
*/ |
32
|
|
|
private function getGraphQLValues(string $enum, string $shortName): array |
33
|
|
|
{ |
34
|
|
|
$values = []; |
35
|
|
|
|
36
|
|
|
foreach ($enum::getAll() as $key => $value) { |
37
|
|
|
$values[$value] = [ |
38
|
|
|
'value' => $value, |
39
|
|
|
'description' => sprintf('Enum type %s::%s', $shortName, $key), |
40
|
|
|
]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $values; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param BaseEnum|string $enum |
48
|
|
|
* @param string $shortName |
49
|
|
|
* |
50
|
|
|
* @return EnumType |
51
|
|
|
*/ |
52
|
|
|
private function createGraphQLEnumType(string $enum, string $shortName): EnumType |
53
|
|
|
{ |
54
|
|
|
return new EnumType([ |
55
|
|
|
'name' => $shortName, |
56
|
|
|
'description' => $shortName . ' type', |
57
|
|
|
'values' => $this->getGraphQLValues($enum, $shortName), |
58
|
|
|
]); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $enum |
63
|
|
|
* @return EnumType |
64
|
|
|
* @throws \ReflectionException |
65
|
|
|
*/ |
66
|
|
|
public function toGraphQL(string $enum): EnumType |
67
|
|
|
{ |
68
|
|
|
if (! array_key_exists($enum, $this->enums)) { |
69
|
|
|
$shortName = (new \ReflectionClass($enum))->getShortName(); |
70
|
|
|
|
71
|
|
|
$this->enums[$enum] = $this->createGraphQLEnumType($enum, $shortName); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $this->enums[$enum]; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|