8000 Handle datetime deserialization in U format · symfony/symfony@3e87d75 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3e87d75

Browse files
committed
Handle datetime deserialization in U format
1 parent 3835573 commit 3e87d75

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,13 @@ public function denormalize(mixed $data, string $type, string $format = null, ar
8383
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
8484
$timezone = $this->getTimezone($context);
8585

86-
if (null === $data || !\is_string($data) || '' === trim($data)) {
86+
$data = match ($dateTimeFormat){
87+
'U' => \is_int($data) ? (string) $data : $data,
88+
'U.u' => \is_float($data) ? (string) $data : $data,
89+
default => $data
90+
};
91+
92+
if (!\is_string($data) || '' === trim($data)) {
8793
throw NotNormalizableValueException::createForUnexpectedDataType('The data is either not an string, an empty string, or null; you should pass a string that can be parsed with the passed format or a valid DateTime string.', $data, [Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
8894
}
8995

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ public function testDenormalize()
178178
$this->assertEquals(new \DateTimeImmutable('2016/01/01', new \DateTimeZone('UTC')), $this->normalizer->denormalize('2016-01-01T00:00:00+00:00', \DateTimeImmutable::class));
179179
$this->assertEquals(new \DateTime('2016/01/01', new \DateTimeZone('UTC')), $this->normalizer->denormalize('2016-01-01T00:00:00+00:00', \DateTime::class));
180180
$this->assertEquals(new \DateTime('2016/01/01', new \DateTimeZone('UTC')), $this->normalizer->denormalize(' 2016-01-01T00:00:00+00:00 ', \DateTime::class));
181+
$this->assertEquals(new \DateTimeImmutable('2023-05-06T17:35:34.000000+0000', new \DateTimeZone('UTC')), $this->normalizer->denormalize(1683394534, \DateTimeImmutable::class, null, [DateTimeNormalizer::FORMAT_KEY => 'U']));
182+
$this->assertEquals(new \DateTimeImmutable('2023-05-06T17:35:34.123400+0000', new \DateTimeZone('UTC')), $this->normalizer->denormalize(1683394534.1234, \DateTimeImmutable::class, null, [DateTimeNormalizer::FORMAT_KEY => 'U.u']));
181183
}
182184

183185
public function testDenormalizeUsingTimezonePassedInConstructor()

0 commit comments

Comments
 (0)
0