55use Attribute ;
66use BackedEnum ;
77use ReflectionType ;
8- use ReflectionUnionType ;
98use SergiX44 \Hydrator \Annotation \UnionResolver ;
109use SergiX44 \Hydrator \Exception \UnsupportedPropertyTypeException ;
1110
1211#[Attribute(Attribute::TARGET_PROPERTY )]
1312class EnumOrScalar extends UnionResolver
1413{
15- public function resolve (ReflectionUnionType $ type , array $ data ): ReflectionType
14+ public function resolve (string $ propertyName , array $ propertyTypes , array $ data ): ReflectionType
1615 {
17- $ types = $ type ->getTypes ();
18- $ enum = array_shift ($ types );
19-
20- if (empty ($ types )) {
16+ $ enum = array_shift ($ propertyTypes );
17+ if (empty ($ propertyTypes )) {
2118 return $ enum ;
2219 }
2320
@@ -32,7 +29,7 @@ public function resolve(ReflectionUnionType $type, array $data): ReflectionType
3229 );
3330 }
3431
35- $ value = array_shift ($ data );
32+ $ value = $ data [ $ propertyName ] ?? array_shift ($ data );
3633 if ((is_string ($ value ) || is_int ($ value )) && $ enumClass ::tryFrom ($ value ) !== null ) {
3734 return $ enum ;
3835 }
@@ -45,17 +42,18 @@ public function resolve(ReflectionUnionType $type, array $data): ReflectionType
4542 default => $ valueType ,
4643 };
4744
48- foreach ($ types as $ t ) {
45+ foreach ($ propertyTypes as $ t ) {
4946 if ($ t ->getName () === $ valueType ) {
5047 return $ t ;
5148 }
5249 }
5350
5451 throw new UnsupportedPropertyTypeException (
5552 sprintf (
56- 'This property can be %s or %s, %s given. ' ,
53+ 'The property "%s" can only be %s or %s, %s given. ' ,
54+ $ propertyName ,
5755 $ enumClass ,
58- implode (' or ' , $ types ),
56+ implode (' or ' , $ propertyTypes ),
5957 $ valueType
6058 )
6159 );
0 commit comments