Skip to content

[Serializer] - constructor denormalize inconsistency #61295

@vencakrecl

Description

@vencakrecl

Symfony version(s) affected

7.3.2

Description

The constructor mapping uses only an exact name match of the property, see the test below

How to reproduce

<?php

declare(strict_types=1);

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class A
{
    public string $camelCase = 'value';
}

class B
{
    public function __construct(public string $camelCase = 'value')
    {
    }
}

class C
{
    public function __construct(public readonly string $camelCase = 'value')
    {
    }
}

#[CoversNothing]
class ExampleTest extends TestCase
{
    #[TestWith([['camelCase' => 'test'], A::class])]
    #[TestWith([['camel_case' => 'test'], A::class])]
    #[TestWith([['camelCase' => 'test'], B::class])]
    #[TestWith([['camel_case' => 'test'], B::class])]
    #[TestWith([['camelCase' => 'test'], C::class])] // error case
    #[TestWith([['camel_case' => 'test'], C::class])]
    public function testBug(array $data, string $class): void
    {
        $normalizers = [
            new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter()),
        ];

        $serializer = new Serializer($normalizers, []);

        $obj = $serializer->denormalize($data, $class, null);

        $this->assertEquals('test', $obj->camelCase);
    }
}

Possible Solution

No response

Additional Context

No response

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