Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Support denormalization of object with variadic constructor typed argument #31436

Closed
@ajgarlag

Description

@ajgarlag

Symfony version(s) affected: 3.4 up to 4.2

Description
When the AbstractNormalizer detects a constructor variadic argument, it ignores the type hint of the argument, so the deserialization process throws a TypeError.

How to reproduce

<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class OrderLine
{
    private $concept;

    public function __construct(string $concept)
    {
        $this->concept = $concept;
    }

    public function getConcept(): string
    {
        return $this->concept;
    }
}

class Order
{
    private $orderLines = [];

    public function __construct(OrderLine ...$orderLines)
    {
        $this->orderLines = $orderLines;
    }

    /** @return OrderLines[] */
    public function getOrderLines(): array
    {
        return $this->orderLines;
    }
}

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$order = new Order(new OrderLine('A'), new OrderLine('B'));
$serializedOrder = $serializer->serialize($order, 'json');
echo $serializedOrder . PHP_EOL;
$deserializedOrder = $serializer->deserialize($serializedOrder, Order::class, 'json');
echo count($deserializedOrder->getOrderLines()) . PHP_EOL;

Expected output:

{"orderLines":[{"concept":"A"},{"concept":"B"}]}
2

Current output:

{"orderLines":[{"concept":"A"},{"concept":"B"}]}
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to Order::__construct() must be an instance of OrderLine, array given in /tmp/lala/bug.php:26
Stack trace:
#0 [internal function]: Order->__construct(Array, Array)
#1 /tmp/lala/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php(387): ReflectionClass->newInstanceArgs(Array)
#2 /tmp/lala/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php(185): Symfony\Component\Serializer\Normalizer\AbstractNormalizer->instantiateObject(Array, 'Order', Array, Object(ReflectionClass), false, 'json')
#3 /tmp/lala/vendor/symfony/symfony/src/Symfony/Component/Serializer/Serializer.php(182): Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer->denormalize(Array, 'Order', 'json', Array)
#4 /tmp/lala/vendor/symfony/symfony/src/Symfony/Component/Serializer/Serializer.php(133): Symfony\Component\Serializer\Serializer->denormalize(Array, 'Order', 'json', Array)
#5 /tmp/lala/bug.php(42): Symfony\Component\ in /tmp/lala/bug.php on line 26

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions