Skip to content

Commit 57cf4bb

Browse files
authored
Merge pull request #651 from vincequeiroz/master
Check nullable fields on handleTypeConversions method
2 parents a7e0f31 + 1fadc0a commit 57cf4bb

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,10 @@ public function hydrateValue($name, $value, $data = null)
272272
{
273273
$value = parent::hydrateValue($name, $value, $data);
274274

275+
if (is_null($value) && method_exists($this->metadata, 'isNullable') && $this->metadata->isNullable($name)) {
276+
return null;
277+
}
278+
275279
return $this->handleTypeConversions($value, $this->metadata->getTypeOfField($name));
276280
}
277281

@@ -535,6 +539,10 @@ function ($item) {
535539
*/
536540
protected function handleTypeConversions($value, $typeOfField)
537541
{
542+
if (is_null($value)) {
543+
return null;
544+
}
545+
538546
switch ($typeOfField) {
539547
case 'boolean':
540548
$value = (bool)$value;

tests/DoctrineModuleTest/Stdlib/Hydrator/DoctrineObjectTypeConversionsTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,4 +621,26 @@ public function testHandleTypeConversionsDecimal()
621621
$this->assertTrue(is_string($entity->getGenericField()));
622622
$this->assertEquals('12345', $entity->getGenericField());
623623
}
624+
625+
public function testHandleTypeConversionsNullable()
626+
{
627+
// When using hydration by value, it will use the public API of the entity to set values (setters)
628+
$this->configureObjectManagerForSimpleEntityWithGenericField(null);
629+
630+
$entity = new Asset\SimpleEntityWithGenericField();
631+
$data = ['genericField' => null];
632+
633+
$entity = $this->hydratorByValue->hydrate($data, $entity);
634+
635+
$this->assertTrue(is_null($entity->getGenericField()));
636+
$this->assertEquals(null, $entity->getGenericField());
637+
638+
$entity = new Asset\SimpleEntityWithGenericField();
639+
$data = ['genericField' => null];
640+
641+
$entity = $this->hydratorByReference->hydrate($data, $entity);
642+
643+
$this->assertTrue(is_null($entity->getGenericField()));
644+
$this->assertEquals(null, $entity->getGenericField());
645+
}
624646
}

0 commit comments

Comments
 (0)