From eb2bc306f776ae236667ace34d99159f89ac9f9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Mon, 2 May 2022 12:10:41 +0200 Subject: [PATCH] prevent duplicates in relationships data fixtures --- .../DataFixtures/ORM/LoadRelationships.php | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/Bundle/ChillPersonBundle/DataFixtures/ORM/LoadRelationships.php b/src/Bundle/ChillPersonBundle/DataFixtures/ORM/LoadRelationships.php index 4fa9802f8..18b2788f6 100644 --- a/src/Bundle/ChillPersonBundle/DataFixtures/ORM/LoadRelationships.php +++ b/src/Bundle/ChillPersonBundle/DataFixtures/ORM/LoadRelationships.php @@ -21,6 +21,7 @@ use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Persistence\ObjectManager; +use function array_key_exists; use function count; class LoadRelationships extends Fixture implements DependentFixtureInterface @@ -34,7 +35,7 @@ class LoadRelationships extends Fixture implements DependentFixtureInterface $this->em = $em; } - public function getDependencies() + public function getDependencies(): array { return [ LoadPeople::class, @@ -42,9 +43,11 @@ class LoadRelationships extends Fixture implements DependentFixtureInterface ]; } - public function load(ObjectManager $manager) + public function load(ObjectManager $manager): void { - for ($i = 0; 15 > $i; ++$i) { + $existing = []; + + for ($i = 0; 20 > $i; ++$i) { $user = $this->getRandomUser(); $date = new DateTimeImmutable(); $relationship = (new Relationship()) @@ -57,6 +60,17 @@ class LoadRelationships extends Fixture implements DependentFixtureInterface ->setUpdatedBy($user) ->setCreatedAt($date) ->setUpdatedAt($date); + + // remove the potential duplicates + $set = $relationship->getFromPerson()->getId() < $relationship->getToPerson()->getId() ? + [$relationship->getFromPerson()->getId(), $relationship->getToPerson()->getId()] : + [$relationship->getToPerson()->getId(), $relationship->getFromPerson()->getId()]; + + if (array_key_exists($set[0], $existing) && array_key_exists($set[1], $existing[$set[0]])) { + continue; + } + + $existing[$set[0]][$existing[$set[1]]] = 1; $manager->persist($relationship); }