8000 [Serializer] Allow `Context` attribute to target class · Issue #49450 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[Serializer] Allow Context attribute to target class #49450
Closed
@kaznovac

Description

@kaznovac

Description

As a developer I'd like to use Context attribute on a class.

In the example bellow serializer will try to set the readonly $type property (it is already set via the constructor from the concrete class.

The solution I'd like is to exclude $type from denormalization. Context attribute on a class would allow this intent to be written in clear form.

Currently I have to annotate with Context each property of the class in question (this is error prone).
I've tried few structural changes on the DTO classes but all of them feel like monkey-patching.

Example

<?php

namespace App\Dto;

use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

#[DiscriminatorMap(
    typeProperty: 'type',
    mapping: [
        PositionPointDto::POSITION_TYPE => PositionPointDto::class,
    ],
)]
#[Context( /* <-- this cannot compile -- */
    denormalizationContext: [
        AbstractNormalizer::IGNORED_ATTRIBUTES => [
            'type',
        ],
    ],
)]
abstract readonly class PositionDto
{
    public const POSITION_TYPE = 'abstract_position';

    protected function __construct(
        public string $type = self::POSITION_TYPE,
    ) {
    }
}
<?php

namespace App\Dto;

final readonly class PositionPointDto extends PositionDto
{
    public const POSITION_TYPE = 'point';

    public function __construct(
        public int $x,
        public int $y,
    ) {
        parent::__construct(
            self::POSITION_TYPE,
        );
    }
}

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