Rabbi_Gerzi/backend/app/Element/UseCases/UpdateElement/UpdatePdfPath.php
2026-06-02 17:00:33 +03:00

71 lines
1.7 KiB
PHP

<?php
namespace App\Element\UseCases\UpdateElement;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader;
class UpdatePdfPath
{
private const MANAGED_FOLDER_PREFIX = 'element-pdfs/';
public function __construct(
private ElementRepository $elementRepository,
private FileUploader $fileUploader,
) {
}
/**
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(UpdatePdfPathRequest $request): Element
{
if ($request->id === null) {
throw new BadRequestException('id is required');
}
if ($request->pdfPath === null) {
throw new BadRequestException('pdfPath is required');
}
$element = $this->elementRepository->find($request->id);
if ($element === null) {
throw new NotFoundException('Element not found');
}
$pdfPath = $this->nullableString($request->pdfPath);
if ($pdfPath === null) {
$this->deleteManagedFile($element->getPdfPath());
}
$element->setPdfPath($pdfPath);
return $this->elementRepository->update($element);
}
private function nullableString(string $value): ?string
{
if ($value === '') {
return null;
}
return $value;
}
private function deleteManagedFile(?string $path): void
{
if ($path === null) {
return;
}
if (! str_starts_with($path, self::MANAGED_FOLDER_PREFIX)) {
return;
}
$this->fileUploader->delete($path);
}
}