1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Drupal\graphql\Plugin\GraphQL\Enums; |
4
|
|
|
|
5
|
|
|
use Drupal\Component\Plugin\PluginBase; |
6
|
|
|
use Drupal\graphql\Plugin\GraphQL\Traits\DescribablePluginTrait; |
7
|
|
|
use Drupal\graphql\Plugin\SchemaBuilderInterface; |
8
|
|
|
use Drupal\graphql\Plugin\TypePluginInterface; |
9
|
|
|
use Drupal\graphql\Plugin\TypePluginManager; |
10
|
|
|
use GraphQL\Type\Definition\EnumType; |
11
|
|
|
|
12
|
|
|
abstract class EnumPluginBase extends PluginBase implements TypePluginInterface { |
13
|
|
|
use DescribablePluginTrait; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* {@inheritdoc} |
17
|
|
|
*/ |
18
|
|
|
public static function createInstance(SchemaBuilderInterface $builder, TypePluginManager $manager, $definition, $id) { |
19
|
|
|
return new EnumType([ |
20
|
|
|
'name' => $definition['name'], |
21
|
|
|
'description' => $definition['description'], |
22
|
|
|
'values' => $definition['values'], |
23
|
|
|
]); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
View Code Duplication |
public function getDefinition() { |
|
|
|
|
30
|
|
|
$definition = $this->getPluginDefinition(); |
31
|
|
|
|
32
|
|
|
return [ |
33
|
|
|
'name' => $definition['name'], |
34
|
|
|
'description' => $this->buildDescription($definition), |
35
|
|
|
'values' => $this->buildEnumValues($definition), |
36
|
|
|
]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param $definition |
41
|
|
|
* |
42
|
|
|
* @return array |
43
|
|
|
*/ |
44
|
|
|
protected function buildEnumValues($definition) { |
45
|
|
|
return array_map(function ($value) use ($definition) { |
46
|
|
|
return [ |
47
|
|
|
'value' => $this->buildEnumValue($value, $definition), |
48
|
|
|
'description' => $this->buildEnumDescription($value, $definition), |
49
|
|
|
]; |
50
|
|
|
}, $definition['values']); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param $value |
55
|
|
|
* @param $definition |
56
|
|
|
* |
57
|
|
|
* @return mixed |
58
|
|
|
*/ |
59
|
|
|
protected function buildEnumValue($value, $definition) { |
60
|
|
|
return is_array($value) ? $value['value'] : $value; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param $value |
65
|
|
|
* @param $definition |
66
|
|
|
* |
67
|
|
|
* @return string |
68
|
|
|
*/ |
69
|
|
|
protected function buildEnumDescription($value, $definition) { |
70
|
|
|
return (string) (is_array($value) ? $value['description'] : ''); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
} |
74
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.