Skip to content

Commit c70bd5e

Browse files
committed
[Serializer] Handle defaultContext for DateTimeNormalizer
1 parent c54cfbb commit c70bd5e

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

Normalizer/DateTimeNormalizer.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,8 @@ public function supportsNormalization($data, string $format = null)
8888
*/
8989
public function denormalize($data, string $type, string $format = null, array $context = [])
9090
{
91-
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
92-
$timezone = $this->getTimezone($context);
93-
9491
if (\is_int($data) || \is_float($data)) {
95-
switch ($dateTimeFormat) {
92+
switch ($context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY] ?? null) {
9693
case 'U': $data = sprintf('%d', $data); break;
9794
case 'U.u': $data = sprintf('%.6F', $data); break;
9895
}
@@ -103,6 +100,9 @@ public function denormalize($data, string $type, string $format = null, array $c
103100
}
104101

105102
try {
103+
$timezone = $this->getTimezone($context);
104+
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
105+
106106
if (null !== $dateTimeFormat) {
107107
$object = \DateTime::class === $type ? \DateTime::createFromFormat($dateTimeFormat, $data, $timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data, $timezone);
108108

Tests/Normalizer/DateTimeNormalizerTest.php

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

283+
public function testDenormalizeTimestampWithFormatInContext()
284+
{
285+
$normalizer = new DateTimeNormalizer();
286+
$denormalizedDate = $normalizer->denormalize(1698202249, \DateTimeInterface::class, null, [DateTimeNormalizer::FORMAT_KEY => 'U']);
287+
288+
$this->assertSame('2023-10-25 02:50:49', $denormalizedDate->format('Y-m-d H:i:s'));
289+
}
290+
291+
public function testDenormalizeTimestampWithFormatInDefaultContext()
292+
{
293+
$normalizer = new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => 'U']);
294+
$denormalizedDate = $normalizer->denormalize(1698202249, \DateTimeInterface::class);
295+
296+
$this->assertSame('2023-10-25 02:50:49', $denormalizedDate->format('Y-m-d H:i:s'));
297+
}
298+
283299
public function testDenormalizeDateTimeStringWithDefaultContextFormat()
284300
{
285301
$format = 'd/m/Y';

0 commit comments

Comments
 (0)