44
55namespace Cortex \JsonSchema \Converters ;
66
7- use BackedEnum ;
87use ReflectionEnum ;
98use Cortex \JsonSchema \Support \DocParser ;
10- use Cortex \JsonSchema \Types \ObjectSchema ;
119use Cortex \JsonSchema \Types \StringSchema ;
1210use Cortex \JsonSchema \Contracts \Converter ;
1311use Cortex \JsonSchema \Types \IntegerSchema ;
@@ -26,17 +24,29 @@ class EnumConverter implements Converter
2624 public function __construct (
2725 protected string $ enum ,
2826 ) {
29- // @phpstan-ignore function.alreadyNarrowedType
30- if (! is_subclass_of ($ this ->enum , BackedEnum::class)) {
27+ $ this ->reflection = new ReflectionEnum ($ this ->enum );
28+
29+ if (! $ this ->reflection ->isBacked ()) {
3130 throw new SchemaException ('Enum must be a backed enum ' );
3231 }
33-
34- $ this ->reflection = new ReflectionEnum ($ this ->enum );
3532 }
3633
37- public function convert (): ObjectSchema
34+ public function convert (): StringSchema | IntegerSchema
3835 {
39- $ schema = new ObjectSchema ();
36+ // Get the basename of the enum namespace
37+ $ enumName = basename (str_replace ('\\' , '/ ' , $ this ->enum ));
38+
39+ // Determine the backing type
40+ $ schema = match ($ this ->reflection ->getBackingType ()?->getName()) {
41+ 'string ' => new StringSchema ($ enumName ),
42+ 'int ' => new IntegerSchema ($ enumName ),
43+ default => throw new SchemaException ('Unsupported enum backing type. Only "int" or "string" are supported. ' ),
44+ };
45+
46+ /** @var non-empty-array<int, string|int> $values */
47+ $ values = array_column ($ this ->enum ::cases (), 'value ' );
48+
49+ $ schema ->enum ($ values );
4050
4151 // Get the description from the doc parser
4252 $ description = $ this ->getDocParser ($ this ->reflection )?->description() ?? null ;
@@ -46,19 +56,7 @@ public function convert(): ObjectSchema
4656 $ schema ->description ($ description );
4757 }
4858
49- // Get the basename of the enum namespace
50- $ parts = explode ('\\' , $ this ->enum );
51- $ enumName = end ($ parts );
52-
53- /** @var non-empty-array<int, string|int> $values */
54- $ values = array_column ($ this ->enum ::cases (), 'value ' );
55-
56- // Determine the backing type
57- return match ($ this ->reflection ->getBackingType ()?->getName()) {
58- 'string ' => $ schema ->properties ((new StringSchema ($ enumName ))->enum ($ values )->required ()),
59- 'int ' => $ schema ->properties ((new IntegerSchema ($ enumName ))->enum ($ values )->required ()),
60- default => throw new SchemaException ('Unsupported enum backing type. Only "int" or "string" are supported. ' ),
61- };
59+ return $ schema ;
6260 }
6361
6462 /**
0 commit comments