106 lines
3 KiB
PHP
106 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Set\UseCases\CreateSetWithRoot;
|
|
|
|
use App\Element\CreateElementDto;
|
|
use App\Element\ElementRepository;
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Set\CreateSetDto;
|
|
use App\Set\Set;
|
|
use App\Set\SetRepository;
|
|
use App\Shared\Files\FileToUpload;
|
|
use App\Shared\Files\Filesystem;
|
|
|
|
class CreateSetWithRoot
|
|
{
|
|
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 ElementRepository $elementRepository,
|
|
private Filesystem $filesystem,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
*/
|
|
public function execute(CreateSetWithRootRequest $request): Set
|
|
{
|
|
if ($request->name === null || $request->name === '') {
|
|
throw new BadRequestException('name is required');
|
|
}
|
|
if ($request->description === null || $request->description === '') {
|
|
throw new BadRequestException('description is required');
|
|
}
|
|
|
|
$iconPath = $this->uploadIconImage($request);
|
|
$set = $this->setRepository->create(new CreateSetDto(
|
|
name: $request->name,
|
|
description: $request->description,
|
|
iconImageUrl: $iconPath,
|
|
));
|
|
|
|
$this->elementRepository->create(new CreateElementDto(
|
|
set: $set,
|
|
title: $set->getName(),
|
|
description: $set->getDescription(),
|
|
iconImageUrl: $iconPath,
|
|
richText: '',
|
|
shortPdfPath: null,
|
|
longPdfPath: null,
|
|
youtubeUrl: null,
|
|
parentElement: null,
|
|
));
|
|
|
|
return $set;
|
|
}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
*/
|
|
private function uploadIconImage(CreateSetWithRootRequest $request): string
|
|
{
|
|
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',
|
|
);
|
|
}
|
|
|
|
$iconImage = new FileToUpload(
|
|
contents: $request->iconImageContents,
|
|
originalName: $request->iconImageOriginalName,
|
|
mimeType: $request->iconImageMimeType,
|
|
sizeBytes: $request->iconImageSizeBytes,
|
|
);
|
|
|
|
return $this->filesystem->upload($iconImage, 'set-icons');
|
|
}
|
|
}
|