Skip to content

[Serializer] Throw InvalidArgumentException if the data needed in the constructor doesn't belong to a backedEnum #47128

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

Merged
merged 1 commit into from
Aug 19, 2022

Conversation

alli83
Copy link
Contributor

@alli83 alli83 commented Jul 30, 2022

Q A
Branch? 5.4
Bug fix? yes
New feature? no
Deprecations? no
Tickets Fix #46977 [Serializer] Collect deserialization errors on enum cause TypeError
License MIT
Doc PR

Targeted case: Deserialization with "collect_denormalization_errors" set but the data to be serialized does not correspond to the scalar value of the targeted enum instance in the object's constructor.
updated in last commit : Keep "from "(in the previous commits I had switched to "tryFrom") to map the data submitted to an enum instance targeted.

Imho, even if the "collect_denormalization_errors" is specified, this type of error seems to have to be caught upstream. By just trying to collect the error we do not prevent the object from being instantiated. But this action is bound to fail because we already know that the data is not valid (checked by the BackedEnumNormalizer). This instantiation 'failure' leads to a confusing/misleading error (i.e. Argument # 1 ($test) must be of type TestEnum, string given) which is not the original error.

@carsonbot
Copy link

Hey!

I see that this is your first PR. That is great! Welcome!

Symfony has a contribution guide which I suggest you to read.

In short:

  • Always add tests
  • Keep backward compatibility (see https://symfony.com/bc).
  • Bug fixes must be submitted against the lowest maintained branch where they apply (see https://symfony.com/releases)
  • Features and deprecations must be submitted against the 6.2 branch.

Review the GitHub status checks of your pull request and try to solve the reported issues. If some tests are failing, try to see if they are failing because of this change.

When two Symfony core team members approve this change, it will be merged and you will become an official Symfony contributor!
If this PR is merged in a lower version branch, it will be merged up to all maintained branches within a few days.

I am going to sit back now and wait for the reviews.

Cheers!

Carsonbot

Copy link
Member

@chalasr chalasr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! I'm not totally sure about the current patch though

@chalasr
Copy link
Member

chalasr commented Jul 31, 2022

/cc @alexandre-daubois as you are the author of that normalizer

@alli83 alli83 force-pushed the issue_46977 branch 2 times, most recently from 62f439b to 3451834 Compare August 17, 2022 13:38
@alli83 alli83 changed the title [Serializer] Return null and handle as InvalidArgumentException instead of ValueError if the data doesn't belong to a backed enum [Serializer] Throw InvalidArgumentException if the data needed in the constructor doesn't belong to a backedEnum Aug 18, 2022
Copy link
Member

@chalasr chalasr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me as it seems to fix the buggy case at hand as proven by the added tests.

@fabpot
Copy link
Member

fabpot commented Aug 19, 2022

Thank you @alli83.

@fabpot fabpot merged commit cb3684e into symfony:5.4 Aug 19, 2022
@alli83 alli83 deleted the issue_46977 branch August 19, 2022 11:09
This was referenced Aug 26, 2022
@fabpot fabpot mentioned this pull request Sep 30, 2022
@issei-m
Copy link
Contributor

issei-m commented Feb 16, 2023

This pull-request doesn't seem to fix the targeted issue.
AFAIK, the issue author (@elliotbruneel) would've wanted BackedEnumNormalizer to throw the PartialDenormalizationException in case a value not corresponding to the enum is attempted to be de-normalized.

While I understood the following argument of @alli83,

By just trying to collect the error we do not prevent the object from being instantiated. But this action is bound to fail because we already know that the data is not valid (checked by the BackedEnumNormalizer).

BackedEnumNormalizer can throw the PartialDenormalizationException as long as the DTO doesn't have the constructor but only state their properties like:

<?php

class SerializerIssueReport extends \PHPUnit\Framework\TestCase
{
    public function testCollectErrorsOnEnum()
    {
        $serializer = new Symfony\Component\Serializer\Serializer(
            [
                new \Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer(),
                new \Symfony\Component\Serializer\Normalizer\ObjectNormalizer(),
            ],
            ['json' => new \Symfony\Component\Serializer\Encoder\JsonEncoder()]
        );

        $this->expectException(\Symfony\Component\Serializer\Exception\PartialDenormalizationException::class);

        $serializer->deserialize('{"test": "invalid"}', DummyObject2::class, 'json', [
            \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true
        ]);
    }
}

// Original one, for this class the pull-req is legit.
class DummyObject {
    public function __construct(public TestEnum $test) {}
}

// For this, PartialDenormalizationException can be thrown.
class DummyObject2 {
    public TestEnum $test;
}

enum TestEnum: String
{
    case Test = "test";
}

PartialDenormalizationException is preferred to InvalidArgumentException under the situation we can use it.

@alli83
Copy link
Contributor Author

alli83 commented Feb 16, 2023

Indeed, we could distinguish the type of exception thrown depending on whether there is a constructor or not.

  • if constructor invalid, the object being not possible to instantiate we could still throw the InvalidArgumentException
  • but throw a NotNormalizableValueException in the case you present above and would be collected as a PartialDenormalizationException.

maybe when calling the instantiateObject from the AbstractNormalizer class we could easily add to the context to identify the presence of a constructor and direct the type of exception to throw ?

thanks for your feedback 🙏

@issei-m
Copy link
Contributor

issei-m commented Feb 17, 2023

@alli83 Thank you for clarification. Could you kindly open a pull-req for it?

@alli83
Copy link
Contributor Author

alli83 commented Feb 17, 2023

@issei-m for sure. I will also take into account this PR #48821

@TerjeBr
Copy link

TerjeBr commented Apr 28, 2023

Hi @alli83 Are you going to make a new PR to correct this? As it is now, we cannot have enums in our Dto's because we get InvalidArgumentException instead of PartialDenormalizationException that is expected when we specify collect_denormalization_errors

@alli83
Copy link
Contributor Author

alli83 commented Apr 28, 2023

@TerjeBr PR #48821 doesn't solve your issue ? I can have a look at it :) sorry for the late reply

@TerjeBr
Copy link

TerjeBr commented Apr 28, 2023

No. My project is locked to symfony 5.4 and PR #48821 is a symfony 6.3 thing.

The thing is that this PR undid the feature done by #42502

@alli83
Copy link
Contributor Author

alli83 commented Apr 28, 2023

indeed. I'm glad to have a look at it then for 5.4 !

@TerjeBr
Copy link

TerjeBr commented Apr 28, 2023

Thanks

@TerjeBr
Copy link

TerjeBr commented Apr 28, 2023

To provide some context where I come from, I first viewed #43047 (comment)
Then I was happy that may be #40830 + #42502 would be a solution to my problem. But then I discovered that it was not working any more because of this change.

(Just to give you the background.)

@alli83
Copy link
Contributor Author

alli83 commented Apr 28, 2023

Would the added test case correspond to your case in #50192 ?

fabpot added a commit that referenced this pull request May 5, 2023
…on outside construct method (alli83)

This PR was merged into the 5.4 branch.

Discussion
----------

[Serializer] backed enum throw notNormalizableValueException outside construct method

| Q             | A
| ------------- | ---
| Branch?       | 5.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | #47128 (comment)
| License       | MIT
| Doc PR        |

PR #47128 (comment) was aiming  to throw  an InvalidArgumentException if a constructor's argument is not a valid backedEnum( knowing an error will be thrown in all case e.g when it will be instantiated).

This PR aims to throw a NotNormalizableValueException  (like it was the case before) if an error occurs on an BackedEnum outside the case of the first PR

So we have two different types of exceptions depending on whether it's an error at the constructor level or not.

Commits
-------

5549493 [Serializer] Throw NotNormalizableValueException if it doesn't concern a backedEnum in construct method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants