Skip to content
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

Denormalizing invalid date or datetime results in TypeError #752

Open
marcovtwout opened this issue Sep 7, 2023 · 1 comment
Open

Denormalizing invalid date or datetime results in TypeError #752

marcovtwout opened this issue Sep 7, 2023 · 1 comment

Comments

@marcovtwout
Copy link

Jane version(s) affected:
7

Description
Properties defined as type string and format date or datetime have unsufficient error handling when denormalizing invalid formats. When attempting to denormalize data that does not follow the required format, the following type of error occurs:

TypeError : Model\Foo::setBar(): Argument #1 ($bar) must be of type ?DateTime, bool given, called in ...\Normalizer\FooNormalizer.php on line ..

How to reproduce

  • Use any OpenAPI v3 spec with a date or datetime field.
  • Generate models and normalizers.
  • Attempt to denormalize an invalid datetime value, such as "01/01/2020" or "foobar".

Cause
The generated Normalizer code looks like this:

class FooNormalizer implements DenormalizerInterface, NormalizerInterface, DenormalizerAwareInterface, NormalizerAwareInterface
{
    (..)

    public function denormalize($data, $class, $format = null, array $context = array())
    {
        (..)

        if (\array_key_exists('bar', $data) && $data['bar'] !== null) {
            $object->setBar(\DateTime::createFromFormat('Y-m-d\\TH:i:sP', $data['bar']));
            unset($data['bar']);
        }

And the generated Model looks like this:

class Bar extends \ArrayObject
{
    (..)

    public function setBar(?\DateTime $bar) : self
    {
        $this->initialized['bar'] = true;
        $this->bar= $bar;
        return $this;
    }
}

When DateTime::createFromFormat fails, it returns false, which is not accepted by setBar which requires ?DateTime

Possible Solution
I think the optimal solution would be to make format validation part of the generated validators. That way invalid formats never reach this part of the denormalization where it's too late to do anything with it.

@marcovtwout marcovtwout added the bug label Sep 7, 2023
@Korbeil
Copy link
Member

Korbeil commented Sep 22, 2023

Thanks for you report, validating date formats is a really good idea indeed ! I'll try to add that when I have time !

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

2 participants