core icon indicating copy to clipboard operation
core copied to clipboard

Nullable collection crashes on normalization

Open jaroslavtyc opened this issue 10 months ago • 1 comments

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.

jaroslavtyc avatar Mar 25 '25 16:03 jaroslavtyc

Hello, I had the exact same problem; I found a faulty configuration that I had set up for another purpose.

Symfony\Component\Serializer\Normalizer\ObjectNormalizer: public: true

By removing this configuration, api-platform was able to rebind the error format (404, 500...)

if it can help...

LoicLEMEUT avatar Jun 17 '25 13:06 LoicLEMEUT