8000 AbstractItemNormalizer does not map basic non-string types correctly in XML and CSV · Issue #3192 · api-platform/core · GitHub
[go: up one dir, main page]

Skip to content
AbstractItemNormalizer does not map basic non-string types correctly in XML and CSV #3192
@warslett

Description

@warslett

API Platform version(s) affected: Observed in 1.2.0

Description
When using XML or CSV encoder types, values are always decoded as strings. This results in errors at denormalisation "The type of the "myFieldName" attribute must be "bool", "string" given." Same issue for float and integer values.

How to reproduce

  1. Create a resource with a boolean value
  2. Enable XML encoder
  3. Post XML to resource endpoint setting boolean value
  4. Observe error

Possible Solution
I have fixed the issue locally by adding some logic to AbstractItemNormalizer::createAttributeValue to infer valid values depending on type:

        if (is_string($value) && 'string' !== $type->getBuiltinType()) {

            if (ctype_digit($value)) {
                if ('float' === $type->getBuiltinType()) {
                    $value = floatval($value);
                }
                if ('int' === $type->getBuiltinType()) {
                    $value = intval($value);
                }
            }

            if ('bool' === $type->getBuiltinType()) {
                if (in_array($value, ['true', 'True', 'T', 't', "1"], true)) {
                    $value = true;
                }
                if (in_array($value, ['false', 'False', 'F', 'f', "0"], true)) {
                    $value = false;
                }
            }
        }

Additional Context
This issue is also present in the Serializer project even though it uses a different implementation: symfony/symfony#33849

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0