Skip to content

Nullable collection crashes on normalization #7050

Open
@jaroslavtyc

Description

@jaroslavtyc

API Platform version(s) affected: v3.4.16

Description
A nullable array of entities crashes on serialization, because API platform core expects only iterable, but not null.

How to reproduce

Call \ApiPlatform\JsonLd\Serializer\ItemNormalizer::normalize on following instance $broken = new ManagerVisitsOriginDashboard();

#[ApiResource(normalizationContext: ['skip_null_values' => false])]
class ManagerVisitsOriginDashboard
{
    /** @var array<PiercingBodyPart>|null */
    #[ApiProperty(readableLink: true)]
    public ?array $bodyParts = null;
}

#[ApiResource]
class PiercingBodyPart {}

Possible Solution
In \ApiPlatform\Serializer\AbstractItemNormalizer::getAttributeValue extend condition

                if (!is_iterable($attributeValue)) {
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
                }

to something like

                if (!is_iterable($attributeValue)) {
                    if ($attributeValue === null && $type->isNullable()) {
                        return null;
                    }
                    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
                }

https://github.com/api-platform/core/blob/main/src/Serializer/AbstractItemNormalizer.php#L700

Additional Context
At first I though that it is connected to normalizationContext: ['skip_null_values' => false], but it behaves the same with skipping of null values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions