Closed
Description
Description
Is there any reason to set the context attribute as final?
My proposal is to remove the final
statement, allowing us to create custom context attributes. Our use-case is typically adding a callback for any object property implementing the attribute. But I can see many other use-case, like simplifying the context attribute when it becomes huge or repeated a lot of time like this:
class MyObject
{
#[Context(
normalizationContext: [
AbstractNormalizer::ATTRIBUTES => [MyCustomNormalizer::class],
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
],
denormalizationContext: [
AbstractNormalizer::ATTRIBUTES => [MyOtherCustomNormalizer::class],
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => false,
AbstractObjectNormalizer::SKIP_NULL_VALUES => false,
],
groups: ['group1', 'group2'],
)]
private ?MyOtherObject $otherObject = null;
#[Context(
normalizationContext: [
AbstractNormalizer::ATTRIBUTES => [MyCustomNormalizer::class],
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
],
denormalizationContext: [
AbstractNormalizer::ATTRIBUTES => [MyOtherCustomNormalizer::class],
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => false,
AbstractObjectNormalizer::SKIP_NULL_VALUES => false,
],
groups: ['group1', 'group2'],
)]
private ?MyOtherObject $otherObject2 = null;
}
Example
Another example is when you want to normalize as you wish your objects.
#[\Attribute(\Attribute::TARGET_PROPERTY|\Attribute::TARGET_METHOD|\Attribute::IS_REPEATABLE)]
class FloatAsString extends C
61E7
ontext
{
public function __construct()
{
parent::__construct(
normalizationContext: [
AbstractNormalizer::CALLBACKS => [
'floatProperty' => fn (float $value): string => (string) $value,
],
],
denormalizationContext: [
AbstractNormalizer::CALLBACKS => [
'floatProperty' => fn (string $value): float => (float) $value,
],
],
);
}
}
class MyObject
{
#[FloatAsString]
private ?MyOtherObject $otherObject = null;
}
Thank you!