diff --git a/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php b/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php index 5f9243a5..0e49aaa1 100644 --- a/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php +++ b/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php @@ -272,6 +272,10 @@ public function hydrateValue($name, $value, $data = null) { $value = parent::hydrateValue($name, $value, $data); + if (is_null($value) && method_exists($this->metadata, 'isNullable') && $this->metadata->isNullable($name)) { + return null; + } + return $this->handleTypeConversions($value, $this->metadata->getTypeOfField($name)); } @@ -535,6 +539,10 @@ function ($item) { */ protected function handleTypeConversions($value, $typeOfField) { + if (is_null($value)) { + return null; + } + switch ($typeOfField) { case 'boolean': $value = (bool)$value; diff --git a/tests/DoctrineModuleTest/Stdlib/Hydrator/DoctrineObjectTypeConversionsTest.php b/tests/DoctrineModuleTest/Stdlib/Hydrator/DoctrineObjectTypeConversionsTest.php index fa4a32d6..6516f16c 100644 --- a/tests/DoctrineModuleTest/Stdlib/Hydrator/DoctrineObjectTypeConversionsTest.php +++ b/tests/DoctrineModuleTest/Stdlib/Hydrator/DoctrineObjectTypeConversionsTest.php @@ -621,4 +621,26 @@ public function testHandleTypeConversionsDecimal() $this->assertTrue(is_string($entity->getGenericField())); $this->assertEquals('12345', $entity->getGenericField()); } + + public function testHandleTypeConversionsNullable() + { + // When using hydration by value, it will use the public API of the entity to set values (setters) + $this->configureObjectManagerForSimpleEntityWithGenericField(null); + + $entity = new Asset\SimpleEntityWithGenericField(); + $data = ['genericField' => null]; + + $entity = $this->hydratorByValue->hydrate($data, $entity); + + $this->assertTrue(is_null($entity->getGenericField())); + $this->assertEquals(null, $entity->getGenericField()); + + $entity = new Asset\SimpleEntityWithGenericField(); + $data = ['genericField' => null]; + + $entity = $this->hydratorByReference->hydrate($data, $entity); + + $this->assertTrue(is_null($entity->getGenericField())); + $this->assertEquals(null, $entity->getGenericField()); + } }