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

Skip to content

Conflict of DiscriminatorMap and Ignore attribute #60839

Open
@VitekSkrip

Description

@VitekSkrip

Symfony version(s) affected

7.1.5

Description

Hi @nicolas-grekas

I probably problem with Ignore attribute and DiscriminatorMap at symfony 7.1.5

Example case:

<?php

declare(strict_types=1);

namespace App\Test;

use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
use Symfony\Component\Serializer\Attribute\Ignore;

#[DiscriminatorMap(
    typeProperty: 'type',
    mapping: [
        'base_payload' => BasePayload::class,
        'new_payload' => ExamplePayload::class,
    ],
)]
readonly class BasePayload
{
    public function __construct(
        protected string $a,
    ) {
    }

    public function getA(): string
    {
        return $this->a;
    }

    #[Ignore]
    public function isAString(): bool
    {
        return is_string($this->a);
    }

}

<?php

declare(strict_types=1);

namespace App\Test;

final readonly class ExamplePayload extends BasePayload
{
    public function __construct(
        string $a,
        protected string $b,
    ) {
        parent::__construct($a);
    }

    public function getB(): string
    {
        return $this->b;
    }
}

Runs this:
$serialized = $this->serializer->serialize($new BasePayload('string'), 'json');

get:
image

But then i drop Ignore attribute - it passes (but with unnecessary key "aString") !!

{"type":"base_payload","a":"string","aString":true}

How to reproduce

<?php

declare(strict_types=1);

namespace App\Test;

use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
use Symfony\Component\Serializer\Attribute\Ignore;

#[DiscriminatorMap(
    typeProperty: 'type',
    mapping: [
        'base_payload' => BasePayload::class,
        'new_payload' => ExamplePayload::class,
    ],
)]
readonly class BasePayload
{
    public function __construct(
        protected string $a,
    ) {
    }

    public function getA(): string
    {
        return $this->a;
    }

    #[Ignore]
    public function isAString(): bool
    {
        return is_string($this->a);
    }

}

<?php

declare(strict_types=1);

namespace App\Test;

final readonly class ExamplePayload extends BasePayload
{
    public function __construct(
        string $a,
        protected string $b,
    ) {
        parent::__construct($a);
    }

    public function getB(): string
    {
        return $this->b;
    }
}

$serialized = $this->serializer->serialize($new BasePayload('string'), 'json');

Possible Solution

I tried to apply changes of PR but it didn't help

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