Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Configuration to ignore getters in ObjectNormalizer #39143

Closed
@christian-kolb

Description

@christian-kolb

Description

The ObjectNormalizer only normalized public properties, but also converts getters into properties (whether there are relevant properties for the getter or not). Which is an issue when you have functions like isEqualTo. Usually you could use the PropertyNormalizer, but then we can't use the following constants:

ObjectNormalizer::SKIP_NULL_VALUES,
ObjectNormalizer::PRESERVE_EMPTY_OBJECTS,

And the ObjectNormalizer contains an option to use the PhpDocExtractor which is needed when using arrays of objects as properties.

I would love to have an option to configure the ObjectNormalizer to not use getters. The best way to use it would be with another context constant like ObjectNormalizer::IGNORE_GETTERS.

Example

Value object to serialize

final class Gender
{
    public const GENDER_MALE = 'MALE';
    public const GENDER_FEMALE = 'FEMALE';
    public const GENDER_DIVERSE = 'DIVERSE';
    public const GENDER_OPTIONS = [
        self::GENDER_MALE,
        self::GENDER_FEMALE,
        self::GENDER_DIVERSE,
    ];

    public string $gender;

    public function __construct(string $gender)
    {
        $this->gender = $gender;
    }

    public function isEqualTo(self $gender): bool
    {
        return $this->gender === $gender->gender;
    }
}
$serializer = new Serializer([
        new ObjectNormalizer(),
    ],[
        new JsonEncoder(),
    ]
);

$json = $serializer->serialize(
    new Gender('MALE'), 
    JsonEncoder::FORMAT, 
    [ObjectNormalizer::IGNORE_GETTERS]
);

Json should be

{"gender":"MALE"}

and not

{"gender":"MALE","equalTo":false}

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