8000 [Serializer] BC - Revert of [bug #54635] broke normalization in our entities · Issue #54933 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[Serializer] BC - Revert of [bug #54635] broke normalization in our entities #54933
Closed as not planned
@vsemak

Description

@vsemak

Symfony version(s) affected

5.4.39

Description

Object deserialization ends up in data lose. Solution worked in all previous versions of symfony/serializer before 5.4.39.

How to reproduce

We need object with reference to list of other objects eg. Room with Participant[].

class Participant
{
    private string $name;

    public function __construct(array $data)
    {
        $this->name = $data['name'] ?? '';
    }

    public function setName(string $name): self
    {
        $this->name = $name;
        return $this;
    }

    public function getName()
    {
        return $this->name;
    }
}

class Room
{
    /** @var Participant[] */
    private array $participants;

    public function __construct(array $data)
    {
        $this->participants = $data['participants'] ?? [];
    }

    public function getParticipants(): array
    {
        return $this->participants;
    }

    public function setParticipants(array $participants): self
    {
        $this->participants = $participants;
        return $this;
    }
}

Serializer configuration:

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoders = [new XmlEncoder(), new JsonEncoder()];

$normalizers = [
    new DateTimeNormalizer(),
    new GetSetMethodNormalizer($classMetadataFactory, null, new PhpDocExtractor()),
    new ObjectNormalizer(
        $classMetadataFactory,
        null,
        null,
        new PhpDocExtractor()
    ),
    new ArrayDenormalizer(),
];

$serializer = new Serializer($normalizers, $encoders);

Possible Solution

To solve issue we need to switch GetSetNormalizer with ObjectNormalizer:

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoders = [new XmlEncoder(), new JsonEncoder()];

$normalizers = [
    new DateTimeNormalizer(),
-   new GetSetMethodNormalizer($classMetadataFactory, null, new PhpDocExtractor()),
    new ObjectNormalizer(
        $classMetadataFactory,
        null,
        null,
        new PhpDocExtractor()
    ),
+   new GetSetMethodNormalizer($classMetadataFactory, null, new PhpDocExtractor()),
    new ArrayDenormalizer(),
];

$serializer = new Serializer($normalizers, $encoders);

Additional Context

No response

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

      0