Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3e401ce

Browse files
author
Jean-Pascal Devierne
committed
Allows the DateTimeNormalizer to use the FORMAT_KEY used in constructor in the denormalize method
1 parent e490db8 commit 3e401ce

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
2727

2828
private $defaultContext;
2929

30+
private $defaultDenormalizationFormat;
31+
3032
private static $supportedTypes = [
3133
\DateTimeInterface::class => true,
3234
\DateTimeImmutable::class => true,
@@ -50,6 +52,8 @@ public function __construct($defaultContext = [], \DateTimeZone $timezone = null
5052
$defaultContext[self::TIMEZONE_KEY] = $timezone;
5153
}
5254

55+
$this->defaultDenormalizationFormat = $defaultContext[self::FORMAT_KEY] ?: null;
56+
5357
$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
5458
}
5559

@@ -90,7 +94,7 @@ public function supportsNormalization($data, $format = null)
9094
*/
9195
public function denormalize($data, $type, $format = null, array $context = [])
9296
{
93-
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
97+
$dateTimeFormat = $context[self::FORMAT_KEY] ?? $this->defaultDenormalizationFormat;
9498
$timezone = $this->getTimezone($context);
9599

96100
if ('' === $data || null === $data) {

src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,16 @@ public function testDenormalizeUsingTimezonePassedInContext($input, $expected, $
242242
$this->assertEquals($expected, $actual);
243243
}
244244

245+
public function testDenormalizeUsingFormatPassedInConstructor()
246+
{
247+
$format = 'd/m/Y';
248+
$string = '01/10/2018';
249+
$date = \DateTime::createFromFormat($format, $string);
250+
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => $format]);
251+
$denormalizedDate = $normalizer->denormalize($date->format($format), \DateTimeInterface::class);
252+
$this->assertEquals($date->diff($denormalizedDate)->days, 0);
253+
}
254+
245255
public function denormalizeUsingTimezonePassedInContextProvider()
246256
{
247257
yield 'with timezone' => [

0 commit comments

Comments
 (0)