Skip to content

Commit a07b902

Browse files
authored
Support nullable date field in HydratorFactory #2753 (#2755)
1 parent bac59cf commit a07b902

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,10 @@ private function generateHydratorClass(ClassMetadata $class, string $hydratorCla
185185
<<<'EOF'
186186
187187
// Field(type: "date")
188-
if (isset($data['%1$s'])) {
188+
if (array_key_exists('%1$s', $data) && ($data['%1$s'] !== null || ($this->class->fieldMappings['%2$s']['nullable'] ?? false))) {
189189
$value = $data['%1$s'];
190190
%3$s
191-
$this->class->reflFields['%2$s']->setValue($document, clone $return);
191+
$this->class->reflFields['%2$s']->setValue($document, $return === null ? null : clone $return);
192192
$hydratedData['%2$s'] = $return;
193193
}
194194

tests/Doctrine/ODM/MongoDB/Tests/Functional/DateTest.php

+13
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,19 @@ public function testDateInstanceChangeWhenValueDifferenceIsSubSecond(): void
8484
self::assertNotEmpty($changeset);
8585
}
8686

87+
public function testNullableDateInstanceValue(): void
88+
{
89+
$user = new User();
90+
$user->setCreatedAt(new DateTime('1985-09-01'));
91+
$this->dm->persist($user);
92+
$this->dm->flush();
93+
$this->dm->clear();
94+
95+
$user = $this->dm->getRepository($user::class)->findOneBy([]);
96+
self::assertInstanceOf(DateTime::class, $user->getCreatedAt());
97+
self::assertNull($user->getDisabledAt());
98+
}
99+
87100
public function testDateInstanceValueChangeDoesCauseUpdateIfValueIsTheSame(): void
88101
{
89102
$user = new User();

tests/Documents/User.php

+8
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ class User extends BaseDocument
3434
#[ODM\Field(type: 'date')]
3535
protected $createdAt;
3636

37+
#[ODM\Field(type: 'date', nullable: true, name: 'disable-at')]
38+
protected ?DateTimeInterface $disabledAt;
39+
3740
/** @var Address|null */
3841
#[ODM\EmbedOne(targetDocument: Address::class)]
3942
protected $address;
@@ -211,6 +214,11 @@ public function getCreatedAt()
211214
return $this->createdAt;
212215
}
213216

217+
public function getDisabledAt(): ?DateTimeInterface
218+
{
219+
return $this->disabledAt;
220+
}
221+
214222
public function getAddress(): ?Address
215223
{
216224
return $this->address;

0 commit comments

Comments
 (0)