Rabbi_Gerzi/backend/app/Element/UseCases/UpdateElement/UpdateIconImage.php

81 lines
2.2 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\FileToUpload;
use App\Shared\Files\FileUploader;
class UpdateIconImage
{
private const ALLOWED_MIME_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
];
private const MAX_SIZE_BYTES = 5 * 1024 * 1024;
public function __construct(
private ElementRepository $elementRepository,
private FileUploader $fileUploader,
) {
}
/**
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(UpdateIconImageRequest $request): Element
{
if ($request->id === null) {
throw new BadRequestException('id is required');
}
if (
$request->iconImageContents === null
|| $request->iconImageOriginalName === null
|| $request->iconImageMimeType === null
|| $request->iconImageSizeBytes === null
) {
throw new BadRequestException('icon image is required');
}
if (
! in_array(
$request->iconImageMimeType,
self::ALLOWED_MIME_TYPES,
true,
)
) {
throw new BadRequestException(
'icon image must be a jpeg, png or webp image',
);
}
if ($request->iconImageSizeBytes > self::MAX_SIZE_BYTES) {
throw new BadRequestException(
'icon image must be 5MB or smaller',
);
}
$element = $this->elementRepository->find($request->id);
if ($element === null) {
throw new NotFoundException('Element not found');
}
$iconImage = new FileToUpload(
contents: $request->iconImageContents,
originalName: $request->iconImageOriginalName,
mimeType: $request->iconImageMimeType,
sizeBytes: $request->iconImageSizeBytes,
);
$path = $this->fileUploader->upload($iconImage, 'element-icons');
$element->setIconImageUrl($path);
return $this->elementRepository->update($element);
}
}