diff --git a/src/Bundle/ChillThirdPartyBundle/Service/ThirdpartyMergeService.php b/src/Bundle/ChillThirdPartyBundle/Service/ThirdpartyMergeService.php index 8c4d0e9ef..dee1f987c 100644 --- a/src/Bundle/ChillThirdPartyBundle/Service/ThirdpartyMergeService.php +++ b/src/Bundle/ChillThirdPartyBundle/Service/ThirdpartyMergeService.php @@ -12,7 +12,9 @@ declare(strict_types=1); namespace Chill\ThirdPartyBundle\Service; use Chill\ThirdPartyBundle\Entity\ThirdParty; +use Doctrine\DBAL\Exception; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; class ThirdpartyMergeService { @@ -20,106 +22,99 @@ class ThirdpartyMergeService public function merge(ThirdParty $toKeep, ThirdParty $toDelete): void { - // Transfer non-duplicate data - $this->transferData($toKeep, $toDelete); + $conn = $this->em->getConnection(); + $conn->beginTransaction(); - // Update linked entities - $this->updateReferences($toKeep, $toDelete); + try { + $queries = array_merge( + $this->transferData($toKeep, $toDelete), + $this->updateReferences($toKeep, $toDelete), + $this->removeThirdparty($toDelete) + ); - $this->em->remove($toDelete); - $this->em->flush(); - } - - private function transferData(ThirdParty $toKeep, ThirdParty $toDelete): void - { - $excludedProperties = ['id', 'createdAt']; - $reflection = new \ReflectionClass(ThirdParty::class); - - foreach ($reflection->getProperties() as $property) { - if (in_array($property->getName(), $excludedProperties, true)) { - continue; + foreach ($queries as $query) { + $conn->executeStatement($query['sql'], $query['params']); } - $toKeepValue = $property->getValue($toKeep); - $toDeleteValue = $property->getValue($toDelete); - - if (null === $toKeepValue && null !== $toDeleteValue) { - $property->setValue($toKeep, $toDeleteValue); - } - - if ($toKeepValue instanceof \Doctrine\Common\Collections\Collection - && $toDeleteValue instanceof \Doctrine\Common\Collections\Collection) { - foreach ($toDeleteValue as $item) { - if (!$toKeepValue->contains($item)) { - $toKeepValue->add($item); - } - } - } + $conn->commit(); + } catch (\Exception $e) { + $conn->rollBack(); + throw $e; } } - private function updateReferences(ThirdParty $toKeep, ThirdParty $toDelete): void + /** + * @throws Exception + */ + private function transferData(ThirdParty $toKeep, ThirdParty $toDelete): array { + $queries = []; + $columns = ['profession', 'firstname', 'name', 'email', 'telephone', 'comment', 'kind', 'contact_data_anonymous', 'types', 'active', 'name_company']; + $metadata = $this->em->getClassMetadata(ThirdParty::class); + + foreach ($columns as $column) { + $columnType = $metadata->getTypeOfField($column); + $condition = ('string' === $columnType || 'text' === $columnType) + ? "({$column} IS NULL OR {$column} = '')" + : "{$column} IS NULL"; + + $queries[] = [ + 'sql' => " + UPDATE chill_3party.third_party + SET {$column} = COALESCE((SELECT {$column} FROM chill_3party.third_party WHERE id = :toDelete), {$column}) + WHERE id = :toKeep AND {$condition}", + 'params' => ['toDelete' => $toDelete->getId(), 'toKeep' => $toKeep->getId()] + ]; + } + + return $queries; + } + + private function updateReferences(ThirdParty $toKeep, ThirdParty $toDelete): array + { + $queries = []; $allMeta = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($allMeta as $meta) { + if ($meta->isMappedSuperclass) { + continue; + } + + $tableName = $meta->getTableName(); foreach ($meta->getAssociationMappings() as $assoc) { - if (ThirdParty::class !== $assoc['targetEntity']) { - continue; // Skip unrelated associations + if (ThirdParty::class !== $assoc['targetEntity'] && ThirdParty::class !== $assoc['sourceEntity']) { + continue; } - $entityClass = $meta->getName(); - $associationField = $assoc['fieldName']; + if ($assoc['type'] & ClassMetadata::TO_ONE) { + $joinColumn = $meta->getSingleAssociationJoinColumnName($assoc['fieldName']); + $sql = "UPDATE {$tableName} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete"; - if ($assoc['type'] & \Doctrine\ORM\Mapping\ClassMetadata::TO_ONE) { - // Handle ManyToOne or OneToOne - $qb = $this->em->createQueryBuilder(); - $qb->update($entityClass, 'e') - ->set("e.{$associationField}", ':toKeep') - ->where("e.{$associationField} = :toDelete") - ->setParameter('toKeep', $toKeep) - ->setParameter('toDelete', $toDelete) - ->getQuery() - ->execute(); + $queries[] = ['sql' => $sql, 'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()]]; } - if ($assoc['type'] & \Doctrine\ORM\Mapping\ClassMetadata::TO_MANY) { - // Handle ManyToMany or OneToMany (inverse side) - $repo = $this->em->getRepository($entityClass); - $linkedEntities = $repo->createQueryBuilder('e') - ->join("e.{$associationField}", 't') - ->where('t = :toDelete') - ->setParameter('toDelete', $toDelete) - ->getQuery() - ->getResult(); - - foreach ($linkedEntities as $entity) { - $getter = 'get'.ucfirst($associationField); - $setter = 'set'.ucfirst($associationField); - $adder = 'add'.ucfirst(rtrim($associationField, 's')); - $remover = 'remove'.ucfirst(rtrim($associationField, 's')); - - if (method_exists($entity, $getter) && method_exists($entity, $setter)) { - // For OneToMany owning side - $collection = $entity->{$getter}(); - if ($collection->contains($toDelete)) { - $collection->removeElement($toDelete); - if (!$collection->contains($toKeep)) { - $collection->add($toKeep); - } - } - } elseif (method_exists($entity, $adder) && method_exists($entity, $remover)) { - // For ManyToMany - $entity->{$remover}($toDelete); - $entity->{$adder}($toKeep); - } - - $this->em->persist($entity); - } + if ($assoc['type'] & ClassMetadata::TO_MANY && isset($assoc['joinTable'])) { + $joinTable = $assoc['joinTable']['name']; + $joinColumn = ThirdParty::class === $assoc['targetEntity'] + ? $assoc['joinTable']['inverseJoinColumns'][0]['name'] + : $assoc['joinTable']['joinColumns'][0]['name']; +//TODO problem remaining for ManyToMany relations when UPDATE triggers a UNIQUE CONSTRAINT...in the case of Thirdparty -> thirdparty_category and thirdparty_center + $queries[] = [ + 'sql' => "UPDATE {$joinTable} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete", + 'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()], + ]; } } } - $this->em->flush(); + return $queries; + } + + public function removeThirdparty(ThirdParty $toDelete): array + { + return [[ + 'sql' => 'DELETE FROM chill_3party.third_party WHERE id = :toDelete', + 'params' => ['toDelete' => $toDelete->getId()], + ]]; } }