Skip to content

incorrect normalization of DiscriminatorMap  #59327

Open
@root-aza

Description

@root-aza

Symfony version(s) affected

5.4.-7.2.

Description

Serializer cannot correctly serialize the same structure but with different property values.

Code:

enum DocumentType: string
{
    case RF_ACTUAL   = 'RF_ACTUAL';
    case RF_PREVIOUS = 'RF_PREVIOUS';
}


#[DiscriminatorMap(
    'type',
    [
        DocumentType::RF_ACTUAL->value   => RussianPassportDocument::class,
        DocumentType::RF_PREVIOUS->value => RussianPassportDocument::class,
    ]
)]
abstract class Document
{
    public function __construct(
        public DocumentType $type,
    ) {}
}


final class RussianPassportDocument extends Document
{
    public function __construct(DocumentType $type)
    {
        if (!in_array($type, [DocumentType::RF_ACTUAL, DocumentType::RF_PREVIOUS])) {
            throw new \InvalidArgumentException('Wrong document type');
        }

        parent::__construct($type);
    }
}


dd(
    $serializer->serialize([new RussianPassportDocument(DocumentType::RF_ACTUAL), new RussianPassportDocument(DocumentType::RF_PREVIOUS)], 'json'), // output: [{"type":"RF_ACTUAL"},{"type":"RF_ACTUAL"}]". WTF?! 🥴
    $serializer->deserialize('[{"type":"RF_ACTUAL"},{"type":"RF_PREVIOUS"}]', Document::class . '[]', 'json'), // output: [{"type":"RF_ACTUAL"},{"type":"RF_PREVIOUS"}]. Great work 😍
);

How to reproduce

Stand for reproducing the problem

Possible Solution

No response

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