delete child elements

This commit is contained in:
Yisroel Baum 2026-06-21 22:13:59 +03:00
parent ac0f404fce
commit f4b42973cb
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
10 changed files with 271 additions and 17 deletions

View file

@ -0,0 +1,83 @@
<?php
namespace App\Element\UseCases\DeleteChildElement;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader;
class DeleteChildElement
{
public function __construct(
private ElementRepository $elementRepository,
private FileUploader $fileUploader,
) {
}
/**
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(DeleteChildElementRequest $request): void
{
if ($request->parentElementId === null) {
throw new BadRequestException('parentElementId is required');
}
if ($request->childElementId === null) {
throw new BadRequestException('childElementId is required');
}
$parentElement = $this->elementRepository->find(
$request->parentElementId
);
if ($parentElement === null) {
throw new NotFoundException('Parent element not found');
}
$childElement = $this->elementRepository->find(
$request->childElementId
);
if ($childElement === null) {
throw new NotFoundException('Child element not found');
}
$actualParentElement = $childElement->getParentElement();
if (
$actualParentElement === null
|| $actualParentElement->getId() !== $parentElement->getId()
) {
throw new BadRequestException(
'Child element does not belong to parent'
);
}
$this->deleteSubtree($childElement);
}
private function deleteSubtree(Element $element): void
{
$childElements = $this->elementRepository->findByParentElement(
$element
);
foreach ($childElements as $childElement) {
$this->deleteSubtree($childElement);
}
$this->deleteManagedFile($element->getIconImageUrl());
$this->deleteManagedFile($element->getShortPdfPath());
$this->deleteManagedFile($element->getLongPdfPath());
$this->elementRepository->delete($element);
}
private function deleteManagedFile(?string $path): void
{
if ($path === null) {
return;
}
$this->fileUploader->delete($path);
}
}