@@ -626,8 +626,11 @@ private function validateAndDenormalizeLegacy(array $types, string $currentClass
626
626
private function validateAndDenormalize (Type $ type , string $ currentClass , string $ attribute , mixed $ data , ?string $ format , array $ context ): mixed
627
627
{
628
628
$ expectedTypes = [];
629
+ $ isUnionType = $ type ->asNonNullable () instanceof UnionType;
630
+ $ e = null ;
629
631
$ extraAttributesException = null ;
630
632
$ missingConstructorArgumentsException = null ;
633
+ $ isNullable = false ;
631
634
632
635
$ types = match (true ) {
633
636
$ type instanceof IntersectionType => throw new LogicException ('Unable to handle intersection type. ' ),
@@ -665,6 +668,18 @@ private function validateAndDenormalize(Type $type, string $currentClass, string
665
668
// That's why we have to transform the values, if one of these non-string basic datatypes is expected.
666
669
$ typeIdentifier = $ t ->getTypeIdentifier ();
667
670
if (\is_string ($ data ) && (XmlEncoder::FORMAT === $ format || CsvEncoder::FORMAT === $ format )) {
671
+ if ('' === $ data ) {
672
+ if (TypeIdentifier::ARRAY === $ typeIdentifier ) {
673
+ return [];
674
+ }
675
+
676
+ if (TypeIdentifier::STRING === $ typeIdentifier ) {
677
+ return '' ;
678
+ }
679
+
680
+ $ isNullable = $ isNullable ?: $ type ->isNullable ();
681
+ }
682
+
668
683
switch ($ typeIdentifier ) {
669
684
case TypeIdentifier::ARRAY :
670
685
if ('' === $ data ) {
@@ -794,17 +809,17 @@ private function validateAndDenormalize(Type $type, string $currentClass, string
794
809
return $ data ;
795
810
}
796
811
} catch (NotNormalizableValueException |InvalidArgumentException $ e ) {
797
- if (!$ type instanceof UnionType ) {
812
+ if (!$ isUnionType && ! $ isNullable ) {
798
813
throw $ e ;
799
814
}
800
815
} catch (ExtraAttributesException $ e ) {
801
- if (!$ type instanceof UnionType ) {
816
+ if (!$ isUnionType && ! $ isNullable ) {
802
817
throw $ e ;
803
818
}
804
819
805
820
$ extraAttributesException ??= $ e ;
806
821
} catch (MissingConstructorArgumentsException $ e ) {
807
- if (!$ type instanceof UnionType ) {
822
+ if (!$ isUnionType && ! $ isNullable ) {
808
823
throw $ e ;
809
824
}
810
825
@@ -824,6 +839,10 @@ private function validateAndDenormalize(Type $type, string $currentClass, string
824
839
throw $ missingConstructorArgumentsException ;
825
840
}
826
841
842
+ if (!$ isUnionType && $ e ) {
843
+ throw $ e ;
844
+ }
845
+
827
846
if ($ context [self ::DISABLE_TYPE_ENFORCEMENT ] ?? $ this ->defaultContext [self ::DISABLE_TYPE_ENFORCEMENT ] ?? false ) {
828
847
return $ data ;
829
848
}
0 commit comments