[Serializer] DateTimeNormalizer handling of null and empty values (returning null or empty instead of new object)

This commit is contained in:
Amrouche Hamza 2017-12-03 15:02:49 +01:00
parent f056b4ef5b
commit 74726f3896
No known key found for this signature in database
GPG Key ID: 6968F2785ED4F012
2 changed files with 22 additions and 0 deletions

View File

@ -67,6 +67,10 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface
{
$dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
if ('' === $data || null === $data) {
throw new UnexpectedValueException('The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.');
}
if (null !== $dateTimeFormat) {
$object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);

View File

@ -91,6 +91,24 @@ class DateTimeNormalizerTest extends TestCase
$this->normalizer->denormalize('invalid date', \DateTimeInterface::class);
}
/**
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
* @expectedExceptionMessage The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.
*/
public function testDenormalizeNullThrowsException()
{
$this->normalizer->denormalize(null, \DateTimeInterface::class);
}
/**
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
* @expectedExceptionMessage The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.
*/
public function testDenormalizeEmptyStringThrowsException()
{
$this->normalizer->denormalize('', \DateTimeInterface::class);
}
/**
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
*/