Skip to content

Commit e4e0086

Browse files
committed
Add Enum support to Str type
1 parent 82a247b commit e4e0086

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

src/Schema/Type/Str.php

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace Tobyz\JsonApiServer\Schema\Type;
44

5+
use BackedEnum;
6+
use UnitEnum;
7+
58
class 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

Comments
 (0)