Closed
Description
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,
);
}
}