Rabbi_Gerzi/backend/app/Element/UseCases/DeleteChildElement/DeleteChildElement.php

83 lines
2.3 KiB
PHP

<?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);
}
}