2
2
3
3
namespace Tobyz \JsonApiServer \Schema \Type ;
4
4
5
+ use BackedEnum ;
6
+ use UnitEnum ;
7
+
5
8
class Str implements Type
6
9
{
7
10
public int $ minLength = 0 ;
@@ -17,6 +20,10 @@ public static function make(): static
17
20
18
21
public function serialize (mixed $ value ): string
19
22
{
23
+ if ($ value instanceof UnitEnum) {
24
+ return $ this ->getEnumValue ($ value );
25
+ }
26
+
20
27
return (string ) $ value ;
21
28
}
22
29
@@ -32,9 +39,12 @@ public function validate(mixed $value, callable $fail): void
32
39
return ;
33
40
}
34
41
35
- if ($ this ->enum !== null && !in_array ($ value , $ this ->enum , true )) {
36
- $ enum = array_map (fn ($ value ) => '" ' . $ value . '" ' , $ this ->enum );
37
- $ fail (sprintf ('must be one of %s ' , implode (', ' , $ enum )));
42
+ if ($ this ->enum !== null ) {
43
+ $ enumValues = array_map ($ this ->getEnumValue (...), $ this ->enum );
44
+ if (!in_array ($ value , $ enumValues , true )) {
45
+ $ enum = array_map (fn ($ value ) => '" ' . $ value . '" ' , $ enumValues );
46
+ $ fail (sprintf ('must be one of %s ' , implode (', ' , $ enum )));
47
+ }
38
48
}
39
49
40
50
if (strlen ($ value ) < $ this ->minLength ) {
@@ -74,7 +84,8 @@ public function schema(): array
74
84
}
75
85
76
86
if ($ this ->enum !== null ) {
77
- $ schema ['enum ' ] = $ this ->enum ;
87
+ $ schema ['enum ' ] = array_map ($ this ->getEnumValue (...), $ this ->enum );
88
+ $ schema ['x-enum-varnames ' ] = array_map ($ this ->getEnumName (...), $ this ->enum );
78
89
}
79
90
80
91
return $ schema ;
@@ -114,4 +125,26 @@ public function enum(?array $enum): static
114
125
115
126
return $ this ;
116
127
}
128
+
129
+ private function getEnumValue (string |UnitEnum $ value ): string
130
+ {
131
+ if ($ value instanceof BackedEnum) {
132
+ return $ value ->value ;
133
+ }
134
+
135
+ if ($ value instanceof UnitEnum) {
136
+ return $ value ->name ;
137
+ }
138
+
139
+ return $ value ;
140
+ }
141
+
142
+ private function getEnumName (string |UnitEnum $ value ): string
143
+ {
144
+ if ($ value instanceof UnitEnum) {
145
+ return $ value ->name ;
146
+ }
147
+
148
+ return $ value ;
149
+ }
117
150
}
0 commit comments