Skip to content

Commit

Permalink
Fixed instances children seting new root instance value when their pa…
Browse files Browse the repository at this point in the history
…rent is moved outside of the previuos root.
  • Loading branch information
ruslanbaidan committed Nov 13, 2024
1 parent 6b72c3e commit f17a7c8
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/Service/AnrInstanceService.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public function patchInstance(Entity\Anr $anr, int $id, array $data): Entity\Ins
/** @var Entity\Instance $instance */
$instance = $this->instanceTable->findByIdAndAnr($id, $anr);

$this->updateInstanceParent($instance, $data);
$this->updateInstanceParentAndItsChildrenRoot($instance, $data);

$this->updatePositions(
$instance,
Expand Down Expand Up @@ -421,16 +421,32 @@ private function updateRisks(Entity\Instance $instance): void
}
}

private function updateInstanceParent(Entity\Instance $instance, array $data): void
private function updateInstanceParentAndItsChildrenRoot(Entity\Instance $instance, array $data): void
{
if (!empty($data['parent']) && $instance->getParent()?->getId() !== $data['parent']) {
/* A new parent is set (or just set if it was empty). */
/** @var Entity\Instance|null $parentInstance */
$parentInstance = $this->instanceTable->findById((int)$data['parent'], false);
if ($parentInstance !== null) {
/* Update children's root instance if changed. */
if ($parentInstance->getRoot()?->getId() !== $instance->getRoot()?->getId()) {
$this->updateRootOfChildrenInstances($instance, $parentInstance->getRoot() ?? $parentInstance);
}
$instance->setParent($parentInstance)->setRoot($parentInstance->getRoot() ?? $parentInstance);
}
} elseif (empty($data['parent']) && $instance->hasParent()) {
/* Parent was set before, and now it set as empty (the instance becomes root). */
$instance->setParent(null)->setRoot(null);
/* Set current instance as root for all its children. */
$this->updateRootOfChildrenInstances($instance, $instance);
}
}

private function updateRootOfChildrenInstances(Entity\Instance $instance, Entity\Instance $rootInstance): void
{
foreach ($instance->getChildren() as $childInstance) {
$this->instanceTable->save($childInstance->setRoot($rootInstance), false);
$this->updateRootOfChildrenInstances($childInstance, $rootInstance);
}
}
}

0 comments on commit f17a7c8

Please sign in to comment.