Skip to content

[Serializer] DiscriminatorMap with multiple interfaces/abstract class #47219

@Caligone

Description

@Caligone

Symfony version(s) affected

6.1

Description

When using the serializer to normalize an object that implements an interface with a DisciminatorMap and also extends from an abstract class, the ObjectSerializer doesn't use the DiscriminatorMap and makes the denormalize process failed.
The abstract class seems to have some sort of prority over the interfaces.
I couldn't find this behavior documented anywhere.

How to reproduce

I have created a repository to reproduce the problem easily: https://github.com/yurplan/serializer-bug-example with a composition example.

Here is a minimal example:

#[DiscriminatorMap(
    typeProperty: 'type',
    mapping: [
        'cat' => Cat::class,
        'dog' => Dog::class,
    ],
)]
interface Animal {}

abstract class AbstractEntity {}

class Cat extends AbstractEntity implements Animal {}

class Dog extends AbstractEntity implements Animal {}

$serializer->deserialize($serializer->serialize(new Cat(), 'json'));

// Throws PHP Fatal error:  Uncaught Symfony\Component\Serializer\Exception\NotNormalizableValueException: Type property "type" not found for the abstract object "Animal". in vendor/symfony/serializer/Exception/NotNormalizableValueException.php:31

Possible Solution

I could create an abstract classes implementing the interfaces and extending from the previous class.
I could also create a normalizer to handle this case (i have seen #47208 (comment)).
But I think this issue could be addressed in the package itself by iterating over the interface and abstract classes when looking for a DiscriminatorMap.
There will still be an issue when 2 DiscriminatorMaps are found with the same key...

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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy