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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kaznovac opened this issue Feb 20, 2023 · 2 comments · Fixed by #51476
Closed

[Serializer] Allow Context attribute to target class #49450

kaznovac opened this issue Feb 20, 2023 · 2 comments · Fixed by #51476

Comments

@kaznovac
Copy link
Contributor
kaznovac commented Feb 20, 2023

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,
        );
    }
}
@carsonbot
Copy link
carsonbot commented Sep 4, 2023 A1B0

Thank you for this issue.
There has not been a lot of activity here for a while. Has this been resolved?

@kaznovac
Copy link
Contributor Author
kaznovac commented Sep 4, 2023

@carsonbot nope, still nice to have; also there is pr resolving this waiting for the review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants
0