Home > database >  How to make property nullable for Symfony Serializer
How to make property nullable for Symfony Serializer

Time:11-27

I'm trying to deserialize to an object with property which might take an array of objects as value or be null.

I have no problem deserializing arrays but I need to deserialize null to an empty array or to null itself.

For example { "items": null }

class A {
    /**
     * @var null|Item[]
     */
    private $items = [];

    /**
     * @return Item[]|null
     */
    public function getItems(): ?array
    {
        return $this->items ?? [];
    }

    /** 
     * @param Item $param
     * @return A
     */
    public function addItem(Item $param)
    {
        if (!is_array($this->items)) $this->items = [];
        if (!in_array($param, $this->items))
            $this->items[] = $param;
        return $this;
    }

//    /** tried with this as well
//     * @param array|null $param
//     * @return A
//     */
//    public function setItems(?array $param)
//    {
//        $this->items = $param ?? [];
//        return $this;
//    }

    /**
     * @param Item $item
     * @return A
     */
    public function removeItem(Item $item): A
    {
        if (!is_array($this->items)) $this->items = [];
        if (in_array($item, $this->items))
            unset($this->items[array_search($item, $this->items)]);
        return $this;
    }

    /**
     * @param Item $item
     * @return bool
     */
    public function hasItem(Item $item): bool
    {
        return in_array($item, $this->items);
    }
}

Serializer looks like this

        $defaultContext = [
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>
                function ($articles, $format, $context) {
                    return $articles->getId();
                },
            AbstractObjectNormalizer::SKIP_NULL_VALUES => false
        ];

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);

        $encoders = [new JsonEncoder()];

       $serializer = new Serializer([
            new ArrayDenormalizer(),
            new DateTimeNormalizer(),
            new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter, null,
                new ReflectionExtractor(), null, null, $defaultContext
            ),
        ], $encoders);

    $a = $serializer->deserialize('{ "items": null }', A::class, 'json');

The error I get when items is null

  [Symfony\Component\Serializer\Exception\InvalidArgumentException]  
  Data expected to be an array, null given.        

Is it possible to have nullable property?

CodePudding user response:

Traced down to the Serializer source code and found three possible options to have a nullable array.

Option 1

Remove addItem, hasItem, removeItem methods and it allows to set null, array, whatever. This is less preffed solution in my case.

Option 2

Adding a constructor helps as well. https://github.com/symfony/serializer/blob/5.3/Normalizer/AbstractNormalizer.php#L381

    /**
     * A constructor.
     * @param array|null $items
     */
    public function __construct($items)
    {
        $this->items = $items ?? [];
    }

Option 3

Extended ArrayDenormalizer and overrided denormalize method to handle nulls

    public function denormalize($data, string $type, string $format = null, array $context = []): array
    {
        if (null === $this->denormalizer) {
            throw new BadMethodCallException('Please set a denormalizer before calling denormalize()!');
        }
        if (!\is_array($data) && !is_null($data)) {
            throw new InvalidArgumentException('Data expected to be an array or null, ' . get_debug_type($data) . ' given.');
        }
        if (!str_ends_with($type, '[]')) {
            throw new InvalidArgumentException('Unsupported class: ' . $type);
        }
        if(is_null($data))
            return [];

        $type = substr($type, 0, -2);

        $builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
        foreach ($data as $key => $value) {
            if (null !== $builtinType && !('is_' . $builtinType)($key)) {
                throw new NotNormalizableValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, get_debug_type($key)));
            }

            $data[$key] = $this->denormalizer->denormalize($value, $type, $format, $context);
        }

        return $data;
    }
  • Related