🌐 AI搜索 & 代理 主页
Skip to content

Commit 608f56f

Browse files
committed
[Serializer] Respect default context in DateTimeNormalizer::denormalize
fixes #29030
1 parent 57f5df5 commit 608f56f

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Symfony/Component/Serializer/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) {

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,18 @@ 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(): void
309+
{
310+
$format = 'd/m/Y';
311+
$string = '01/10/2018';
312+
$date = \DateTime::createFromFormat($format, $string);
313+
314+
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => $format]);
315+
$denormalizedDate = $normalizer->denormalize($date->format($format), \DateTimeInterface::class);
316+
317+
$this->assertEquals($date->diff($denormalizedDate)->days, 0);
318+
}
319+
308320
public function testDenormalizeFormatMismatchThrowsException()
309321
{
310322
$this->expectException(UnexpectedValueException::class);

0 commit comments

Comments
 (0)