Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Denormalizer doesn't support parsing string value for boolean type or provides a way to extend denormalizer for scalar types #42715

Closed
@aurimasniekis

Description

@aurimasniekis

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 0or 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:

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions