8000 [Serializer] Set context attribute as not final · Issue #45106 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[Serializer] Set context attribute as not final #45106
Closed
@benjaminmal

Description

@benjaminmal

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 Context
{
    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!

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