normalization of date: allow null

This commit is contained in:
Julien Fastré 2021-12-16 22:01:35 +01:00
parent 06cbe8325c
commit e0bed186b8

View File

@ -17,6 +17,7 @@ use DateTimeInterface;
use IntlDateFormatter; use IntlDateFormatter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface; use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use function array_key_exists; use function array_key_exists;
@ -36,15 +37,20 @@ class DateNormalizer implements ContextAwareNormalizerInterface, DenormalizerInt
public function denormalize($data, string $type, ?string $format = null, array $context = []) public function denormalize($data, string $type, ?string $format = null, array $context = [])
{ {
if (null === $data) {
return null;
}
switch ($type) { switch ($type) {
case DateTime::class: case DateTime::class:
return DateTime::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']); return DateTime::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']);
case DateTimeInterface::class: case DateTimeInterface::class:
case DateTimeImmutable::class: case DateTimeImmutable::class:
default:
return DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']); return DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']);
} }
throw new UnexpectedValueException();
} }
public function normalize($date, ?string $format = null, array $context = []) public function normalize($date, ?string $format = null, array $context = [])