Skip to content

Commit d1acd9b

Browse files
committed
[Serializer] Respect default context in DateTimeNormalizer::denormalize
fixes #29030
1 parent 5cb0dc3 commit d1acd9b

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Normalizer/DateTimeNormalizer.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,16 @@ public function denormalize($data, $type, $format = null, array $context = [])
113113
throw new NotNormalizableValueException(sprintf('Parsing datetime string "%s" using format "%s" resulted in %d errors: ', $data, $dateTimeFormat, $dateTimeErrors['error_count'])."\n".implode("\n", $this->formatDateTimeErrors($dateTimeErrors['errors'])));
114114
}
115115

116+
$defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;
117+
118+
if (null !== $defaultDateTimeFormat) {
119+
$object = \DateTime::class === $type ? \DateTime::createFromFormat($defaultDateTimeFormat, $data, $timezone) : \DateTimeImmutable::createFromFormat($defaultDateTimeFormat, $data, $timezone);
120+
121+
if (false !== $object) {
122+
return $object;
123+
}
124+
}
125+
116126
try {
117127
return \DateTime::class === $type ? new \DateTime($data, $timezone) : new \DateTimeImmutable($data, $timezone);
118128
} catch (\Exception $e) {

Tests/Normalizer/DateTimeNormalizerTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,28 @@ public function testDenormalizeDateTimeStringWithSpacesUsingFormatPassedInContex
305305
$this->normalizer->denormalize(' 2016.01.01 ', \DateTime::class, null, [DateTimeNormalizer::FORMAT_KEY => 'Y.m.d|']);
306306
}
307307

308+
public function testDenormalizeDateTimeStringWithDefaultContextFormat()
309+
{
310+
$format = 'd/m/Y';
311+
$string = '01/10/2018';
312+
313+
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => $format]);
314+
$denormalizedDate = $normalizer->denormalize($string, \DateTimeInterface::class);
315+
316+
$this->assertSame('01/10/2018', $denormalizedDate->format($format));
317+
}
318+
319+
public function testDenormalizeDateTimeStringWithDefaultContextAllowsErrorFormat()
320+
{
321+
$format = 'd/m/Y'; // the default format
322+
$string = '2020-01-01'; // the value which is in the wrong format, but is accepted because of `new \DateTime` in DateTimeNormalizer::denormalize
323+
324+
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => $format]);
325+
$denormalizedDate = $normalizer->denormalize($string, \DateTimeInterface::class);
326+
327+
$this->assertSame('2020-01-01', $denormalizedDate->format('Y-m-d'));
328+
}
329+
308330
public function testDenormalizeFormatMismatchThrowsException()
309331
{
310332
$this->expectException(UnexpectedValueException::class);

0 commit comments

Comments
 (0)