93 lines
2.5 KiB
PHP
93 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Set\UseCases\UpdateSet;
|
|
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Exceptions\NotFoundException;
|
|
use App\Set\Set;
|
|
use App\Set\SetRepository;
|
|
use App\Shared\Files\FileToUpload;
|
|
use App\Shared\Files\Filesystem;
|
|
|
|
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 SetRepository $setRepository,
|
|
private Filesystem $filesystem,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws NotFoundException
|
|
*/
|
|
public function execute(UpdateIconImageRequest $request): Set
|
|
{
|
|
if ($request->id === null) {
|
|
throw new BadRequestException('setId is required');
|
|
}
|
|
|
|
if (
|
|
$request->fileContents === null
|
|
|| $request->fileOriginalName === null
|
|
|| $request->fileMimeType === null
|
|
|| $request->fileSizeBytes === null
|
|
) {
|
|
throw new BadRequestException('icon image is required');
|
|
}
|
|
|
|
if (
|
|
! in_array(
|
|
$request->fileMimeType,
|
|
self::ALLOWED_MIME_TYPES,
|
|
true,
|
|
)
|
|
) {
|
|
throw new BadRequestException(
|
|
'icon image must be a jpeg, png or webp image',
|
|
);
|
|
}
|
|
|
|
if ($request->fileSizeBytes > self::MAX_SIZE_BYTES) {
|
|
throw new BadRequestException(
|
|
'icon image must be 5MB or smaller',
|
|
);
|
|
}
|
|
|
|
$set = $this->setRepository->find($request->id);
|
|
if ($set === null) {
|
|
throw new NotFoundException('Set not found');
|
|
}
|
|
|
|
$oldIconImageUrl = $set->getIconImageUrl();
|
|
$iconImage = new FileToUpload(
|
|
contents: $request->fileContents,
|
|
originalName: $request->fileOriginalName,
|
|
mimeType: $request->fileMimeType,
|
|
sizeBytes: $request->fileSizeBytes,
|
|
);
|
|
$path = $this->filesystem->upload($iconImage, 'set-icons');
|
|
$set->setIconImageUrl($path);
|
|
$updatedSet = $this->setRepository->update($set);
|
|
$this->deleteManagedSetIcon($oldIconImageUrl);
|
|
|
|
return $updatedSet;
|
|
}
|
|
|
|
private function deleteManagedSetIcon(string $path): void
|
|
{
|
|
if (! str_starts_with($path, 'set-icons/')) {
|
|
return;
|
|
}
|
|
|
|
$this->filesystem->delete($path);
|
|
}
|
|
}
|