Skip to content

Allow GetSetMethodNormalizer in Serializer to be aware of type hinted parameters #19935

Closed
@miguelsimoes

Description

@miguelsimoes

When using the Serializer with the GetSetMethodNormalizer, it could be important that, on deserialize/denormalize, if the setters have type hint of the argument that the value could be converted to it.

A simple approach (do not mind the naming convention) would be to replace

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php#L64-L66, which reads:

if (in_array($setter, $classMethods) && !$reflectionClass->getMethod($setter)->isStatic()) {
    $object->$setter($value);
}

With something like:

if (in_array($setter, $classMethods) && !$reflectionClass->getMethod($setter)->isStatic()) {
    $parameters = $reflectionClass->getMethod($setter)->getParameters();
    $typeHint = $parameters[0]->getClass();

    if ($typeHint && class_exists($typeHint->name) && !$value instanceof $typeHint->name) {
        $typeHintedClassName = $typeHinted->name;
        $value = new $typeHintedClassName($value);
    }
    $object->$setter($value);
}

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