diff --git a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php index d22a3463ccdad..181124444fb1a 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php @@ -27,6 +27,8 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, private $defaultContext; + private $defaultDenormalizationFormat; + private static $supportedTypes = [ \DateTimeInterface::class => true, \DateTimeImmutable::class => true, @@ -50,6 +52,8 @@ public function __construct($defaultContext = [], \DateTimeZone $timezone = null $defaultContext[self::TIMEZONE_KEY] = $timezone; } + $this->defaultDenormalizationFormat = $defaultContext[self::FORMAT_KEY] ?? null; + $this->defaultContext = array_merge($this->defaultContext, $defaultContext); } @@ -90,7 +94,7 @@ public function supportsNormalization($data, $format = null) */ public function denormalize($data, $type, $format = null, array $context = []) { - $dateTimeFormat = $context[self::FORMAT_KEY] ?? null; + $dateTimeFormat = $context[self::FORMAT_KEY] ?? $this->defaultDenormalizationFormat; $timezone = $this->getTimezone($context); if ('' === $data || null === $data) { diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php index f4669b134e71e..b05e1b8ab4088 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php @@ -242,6 +242,16 @@ public function testDenormalizeUsingTimezonePassedInContext($input, $expected, $ $this->assertEquals($expected, $actual); } + public function testDenormalizeUsingFormatPassedInConstructor() + { + $format = 'd/m/Y'; + $string = '01/10/2018'; + $date = \DateTime::createFromFormat($format, $string); + $normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => $format]); + $denormalizedDate = $normalizer->denormalize($date->format($format), \DateTimeInterface::class); + $this->assertEquals($date->diff($denormalizedDate)->days, 0); + } + public function denormalizeUsingTimezonePassedInContextProvider() { yield 'with timezone' => [
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: