From 5cca368718fd40c34676c2cead3b167037a1a200 Mon Sep 17 00:00:00 2001 From: Jonathan Petitcolas Date: Wed, 23 Oct 2013 17:26:41 +0200 Subject: [PATCH] Deal with Doctrine entity having a one-to-one nullable relationship --- src/Faker/ORM/Doctrine/EntityPopulator.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Faker/ORM/Doctrine/EntityPopulator.php b/src/Faker/ORM/Doctrine/EntityPopulator.php index a796dd65..e692075f 100644 --- a/src/Faker/ORM/Doctrine/EntityPopulator.php +++ b/src/Faker/ORM/Doctrine/EntityPopulator.php @@ -99,21 +99,29 @@ class EntityPopulator $relatedClass = $this->class->getAssociationTargetClass($assocName); - $unique = false; + $unique = $optional = false; $mappings = $this->class->getAssociationMappings(); foreach ($mappings as $mapping) { if ($mapping['targetEntity'] == $relatedClass) { if ($mapping['type'] == ClassMetadata::ONE_TO_ONE) { $unique = true; + $optional = $mapping['joinColumns'][0]['nullable']; break; } } } $index = 0; - $formatters[$assocName] = function($inserted) use ($relatedClass, &$index, $unique) { + $formatters[$assocName] = function($inserted) use ($relatedClass, &$index, $unique, $optional) { if ($unique && isset($inserted[$relatedClass])) { - return $inserted[$relatedClass][$index++]; + $related = null; + if (isset($inserted[$relatedClass][$index]) || !$optional) { + $related = $inserted[$relatedClass][$index]; + } + + $index++; + + return $related; } elseif (isset($inserted[$relatedClass])) { return $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)]; }