@@ -56,6 +56,13 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
56
56
*/
57
57
public const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement ' ;
58
58
59
+ /**
60
+ * While denormalizing, convert scalar types to the expected type.
61
+ *
62
+ * Enabled by default for the XML and CSV format, because all basic datatypes are represented as strings.
63
+ */
64
+ public const ENABLE_TYPE_CONVERSION = 'enable_type_conversion ' ;
65
+
59
66
/**
60
67
* Flag to control whether fields with the value `null` should be output
61
68
* when normalizing or omitted.
@@ -320,6 +327,10 @@ public function denormalize(mixed $data, string $type, string $format = null, ar
320
327
return null ;
321
328
}
322
329
330
+ if (!isset ($ context [self ::ENABLE_TYPE_CONVERSION ]) && (XmlEncoder::FORMAT === $ format || CsvEncoder::FORMAT === $ format )) {
331
+ $ context [self ::ENABLE_TYPE_CONVERSION ] = true ;
332
+ }
333
+
323
334
$ allowedAttributes = $ this ->getAllowedAttributes ($ type , $ context , true );
324
335
$ normalizedData = $ this ->prepareForDenormalization ($ data );
325
336
$ extraAttributes = [];
@@ -461,7 +472,7 @@ private function validateAndDenormalize(array $types, string $currentClass, stri
461
472
// In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
462
473
// if a value is meant to be a string, float, int or a boolean value from the serialized representation.
463
474
// That's why we have to transform the values, if one of these non-string basic datatypes is expected.
464
- if (\is_string ($ data ) && (XmlEncoder:: FORMAT === $ format || CsvEncoder:: FORMAT === $ format )) {
475
+ if (\is_string ($ data ) && ($ context [ self :: ENABLE_TYPE_CONVERSION ] ?? false )) {
465
476
if ('' === $ data ) {
466
477
if (Type::BUILTIN_TYPE_ARRAY === $ builtinType = $ type ->getBuiltinType ()) {
467
478
return [];
@@ -595,7 +606,7 @@ private function validateAndDenormalize(array $types, string $currentClass, stri
595
606
throw $ missingConstructorArgumentsException ;
596
607
}
597
608
598
- if ($ data === '' && !$ hasNonObjectType && (XmlEncoder:: FORMAT === $ format || CsvEncoder:: FORMAT === $ format )) {
609
+ if ($ data === '' && !$ hasNonObjectType && ($ context [ self :: ENABLE_TYPE_CONVERSION ] ?? false )) {
599
610
return null ;
600
611
} elseif (!$ isUnionType && isset ($ e )) {
601
612
throw $ e ;
0 commit comments