/
Enum.php
132 lines (112 loc) · 3.18 KB
/
Enum.php
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
namespace SilverStripe\GraphQL\Schema\Type;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\GraphQL\Schema\Interfaces\SchemaValidator;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\ORM\ArrayLib;
/**
* Abstraction for enum types
*/
class Enum extends Type implements SchemaValidator
{
private string $name;
private array $values;
private ?string $description;
public function __construct(string $name, array $values, ?string $description = null)
{
parent::__construct($name);
$this->setValues($values);
$this->setDescription($description);
}
/**
* @throws SchemaBuilderException
*/
public function getValueList(): array
{
$list = [];
$values = $this->getValues();
if (!ArrayLib::is_associative($values)) {
$entries = array_values($values ?? []);
$values = array_combine($entries ?? [], $entries ?? []);
}
foreach ($values as $key => $val) {
$value = null;
$description = null;
if (is_array($val)) {
Schema::assertValidConfig($val, ['value', 'description']);
$value = $val['value'];
$description = $val['description'] ?? null;
} else {
$value = $val;
}
$list[] = [
'Key' => static::sanitise($key),
'Value' => $value,
'Description' => $description,
];
}
return $list;
}
/**
* @throws SchemaBuilderException
*/
public function validate(): void
{
Schema::invariant(
!empty($this->getValueList()),
'Enum type %s has no values defined',
$this->getName()
);
$rx = '/^[_a-zA-Z][_a-zA-Z0-9]*$/';
foreach ($this->getValueList() as $item) {
Schema::invariant(
preg_match($rx ?? '', $item['Key'] ?? ''),
'Key "%s" for "%s" is not valid. Must match %s',
$item['Key'],
$this->getName(),
$rx
);
}
}
public function getValues(): array
{
return $this->values;
}
public function setValues(array $values): self
{
$this->values = $values;
return $this;
}
/**
* @param mixed $val
*/
public function addValue(string $key, $val = null): self
{
if ($val === null) {
$this->values[$key] = $key;
} else {
$this->values[$key] = $val;
}
return $this;
}
public function removeValue(string $key): self
{
unset($this->values[$key]);
return $this;
}
public function getSignature(): string
{
$components = [
$this->getName(),
$this->values,
$this->getDescription(),
];
return md5(json_encode($components) ?? '');
}
public static function sanitise(string $str): string
{
$str = preg_replace('/\s+/', '_', $str ?? '');
$str = preg_replace('/[^A-Za-z0-9_]/', '', $str ?? '');
return $str;
}
}