Skip to content

Serializer: type casting for denormalization to public properties #41435

@SpiGAndromeda

Description

@SpiGAndromeda

Description
The Symfony serializer supports type casting at denormalization if getters, setters and issers are used in the target class. Unfortunatly, it doesn't support that casting (of primitive types) with public typed properties. The PropertyInfo component should be able to deliver the necessary information.

Example
I hit this problem when trying to deserialize a request query into a DTO with public properties.

<?php

declare(strict_types=1);

use Symfony\Component\Validator\Constraints as Assert;

final class SearchRequest
{

    #[Assert\NotBlank(allowNull: true)]
    public ?string $addressCity = null;

    /**
     * @Assert\NotBlank(allowNull = true)
     * @Assert\AtLeastOneOf({@Assert\IsNull, @Assert\Regex(ZipCode::ZIP_CODE_PATTERN)})
     * TODO: replace this annotations with PHP8 attributes as soon as nesting is possible.
     *
     * @see https://github.com/symfony/symfony/issues/38503
     */
    public ?string $addressZipCode = null;
    #[Assert\NotBlank(allowNull: true)]
    public ?string $name = null;
    #[Assert\GreaterThanOrEqual(1)]
    public int $page = 1;
    public bool $pagination = true;
    #[Assert\Choice(choices: Type::ALLOWED_TYPES)]
    public ?int $type = null;
}

The non-string attributes are skipped in the deserialization process with only using denormalize. Complete deserialization for query strings, would be nice too. But that's a different story.

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