-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
Description
I am not really sure if this is a bug or feature request.
Symfony version(s) affected: All
Description
When using denormalizer with array input, and mapping to type with a boolean field doesn't support to parse string values like:
"true", "on", "yes", "1" // => true
"false", "off", "no", "0", "" // => false
It is possible to go around this using attribute: AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true
and using values like 0
or 1
but any other string value will always be cast to true because of PHP true logic (https://www.php.net/manual/en/types.comparisons.php).
I thought I would be able to fix this issue by implementing a custom denormalizer, but type properties are not sent through denormalizers, and only the whole type.
This logic is implemented for xml/csv types:
symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php
Lines 432 to 441 in e34cd7d
case Type::BUILTIN_TYPE_BOOL: | |
// according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1" | |
if ('false' === $data || '0' === $data) { | |
$data = false; | |
} elseif ('true' === $data || '1' === $data) { | |
$data = true; | |
} else { | |
throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $currentClass, $data)); | |
} | |
break; |
I think the most appropriate way would be to implement a custom attribute to handle this specific case.
I will create a pull request with this implemented logic as an example of what I think can be done.