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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
aurimasniekis opened this issue Aug 25, 2021 · 5 comments

Comments

@aurimasniekis
Copy link
Contributor

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.

@aurimasniekis
Copy link
Contributor Author

aurimasniekis commented Aug 25, 2021

Here is the pull request #42716

@carsonbot
Copy link

Thank you for this issue.
There has not been a lot of activity here for a while. Has this been resolved?

@carsonbot
Copy link

Friendly ping? Should this still be open? I will close if I don't hear anything.

@carsonbot
Copy link

Hey,

I didn't hear anything so I'm going to close it. Feel free to comment if this is still relevant, I can always reopen!

@TerjeBr
Copy link

TerjeBr commented Sep 14, 2023

Can we please revive this issue. This is exactly the same problem that I have, and we need it for our project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants