Skip to content

[Serializer] Different name conversion strategy is used during denormalization, depending on whether you use properties or a constructor #58583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
gremo opened this issue Oct 16, 2024 · 4 comments

Comments

@gremo
Copy link

gremo commented Oct 16, 2024

Symfony version(s) affected

7.1

Description

A different name conversion strategy is used during denormalization, depending on whether you use properties or a constructor.

How to reproduce

$normalizer = new ObjectNormalizer(
    nameConverter: new CamelCaseToSnakeCaseNameConverter(),
    propertyTypeExtractor: new ReflectionExtractor(),
);

Given this normalizer, with the following class:

class Course
{
    public int $totalLessons;
}
// both works!
dump($n->denormalize(['totalLessons' => 10], Course::class));
dd($n->denormalize(['total_lessons' => 10], Course::class));

image

Now let's use the constructor:

class Course
{
    public function __construct(
        public readonly int $totalLessons,
    ) {
    }
}
// works
dd($n->denormalize(['total_lessons' => 10], Course::class));

// not working! MissingConstructorArgumentsException:
dump($n->denormalize(['totalLessons' => 10], Course::class));

MissingConstructorArgumentsException: "Cannot create an instance of "App\Model\Course" from serialized data because its constructor requires the following parameters to be present : "$totalLessons"." at AbstractNormalizer.php line 417.

Possible Solution

The name converter is applied to the constructor argument, so totalLessons become total_lessons and the exception is thrown.

Additional Context

Is this correct? Do we apply different logic depending only on whether we are using properties or a constructor?

@gremo
Copy link
Author

gremo commented Oct 30, 2024

Any update on this?

@welcoMattic
Copy link
Member

I'm wondering where is the bug, either:

  • $n->denormalize(['totalLessons' => 10], Course::class) on Course class with public property works, but is should not
  • As you mentioned, $n->denormalize(['totalLessons' => 10], Course::class) is not working, but it should

Maybe @mtarld, @Korbeil or @dunglas could have a look here?

@carsonbot
Copy link

Hey, thanks for your report!
There has not been a lot of activity here for a while. Is this bug still relevant? Have you managed to find a workaround?

@carsonbot
Copy link

Just a quick reminder to make a comment on this. If I don't hear anything I'll close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants