22
33namespace Tobyz \JsonApiServer \Schema \Type ;
44
5+ use BackedEnum ;
6+ use UnitEnum ;
7+
58class Str implements Type
69{
710 public int $ minLength = 0 ;
@@ -17,6 +20,10 @@ public static function make(): static
1720
1821 public function serialize (mixed $ value ): string
1922 {
23+ if ($ value instanceof UnitEnum) {
24+ return $ this ->getEnumValue ($ value );
25+ }
26+
2027 return (string ) $ value ;
2128 }
2229
@@ -32,9 +39,12 @@ public function validate(mixed $value, callable $fail): void
3239 return ;
3340 }
3441
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+ }
3848 }
3949
4050 if (strlen ($ value ) < $ this ->minLength ) {
@@ -74,7 +84,8 @@ public function schema(): array
7484 }
7585
7686 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 );
7889 }
7990
8091 return $ schema ;
@@ -114,4 +125,26 @@ public function enum(?array $enum): static
114125
115126 return $ this ;
116127 }
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+ }
117150}
0 commit comments