71 lines
1.7 KiB
PHP
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 UpdateIconImageUrl
|
|
{
|
|
private const MANAGED_FOLDER_PREFIX = 'element-icons/';
|
|
|
|
public function __construct(
|
|
private ElementRepository $elementRepository,
|
|
private FileUploader $fileUploader,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws NotFoundException
|
|
*/
|
|
public function execute(UpdateIconImageUrlRequest $request): Element
|
|
{
|
|
if ($request->id === null) {
|
|
throw new BadRequestException('id is required');
|
|
}
|
|
|
|
if ($request->iconImageUrl === null) {
|
|
throw new BadRequestException('iconImageUrl is required');
|
|
}
|
|
|
|
$element = $this->elementRepository->find($request->id);
|
|
if ($element === null) {
|
|
throw new NotFoundException('Element not found');
|
|
}
|
|
|
|
$iconImageUrl = $this->nullableString($request->iconImageUrl);
|
|
if ($iconImageUrl === null) {
|
|
$this->deleteManagedFile($element->getIconImageUrl());
|
|
}
|
|
|
|
$element->setIconImageUrl($iconImageUrl);
|
|
|
|
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);
|
|
}
|
|
}
|