Skip to content

Commit 233ad77

Browse files
author
Amrouche Hamza
committed
[Serializer] DateTimeNormalizer handling of null and empty values (returning null or empty instead of new object)
1 parent f056b4e commit 233ad77

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

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

+5-1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ public function denormalize($data, $class, $format = null, array $context = arra
6767
{
6868
$dateTimeFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : null;
6969

70+
if ('' === $data) {
71+
return $data;
72+
}
73+
7074
if (null !== $dateTimeFormat) {
7175
$object = \DateTime::class === $class ? \DateTime::createFromFormat($dateTimeFormat, $data) : \DateTimeImmutable::createFromFormat($dateTimeFormat, $data);
7276

@@ -103,7 +107,7 @@ public function supportsDenormalization($data, $type, $format = null)
103107
\DateTime::class => true,
104108
);
105109

106-
return isset($supportedTypes[$type]);
110+
return isset($supportedTypes[$type]) && is_string($data);
107111
}
108112

109113
/**

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

+6
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ public function testSupportsDenormalization()
6767
$this->assertTrue($this->normalizer->supportsDenormalization('2016-01-01T00:00:00+00:00', \DateTime::class));
6868
$this->assertTrue($this->normalizer->supportsDenormalization('2016-01-01T00:00:00+00:00', \DateTimeImmutable::class));
6969
$this->assertFalse($this->normalizer->supportsDenormalization('foo', 'Bar'));
70+
$this->assertFalse($this->normalizer->supportsDenormalization(null, \DateTimeImmutable::class));
7071
}
7172

7273
public function testDenormalize()
@@ -91,6 +92,11 @@ public function testDenormalizeInvalidDataThrowsException()
9192
$this->normalizer->denormalize('invalid date', \DateTimeInterface::class);
9293
}
9394

95+
public function testDenormalizeWithNullAndEmptyString()
96+
{
97+
$this->assertSame('', $this->normalizer->denormalize('', \DateTimeInterface::class));
98+
}
99+
94100
/**
95101
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
96102
*/

0 commit comments

Comments
 (0)