Leonid Nikitin b7d0a2453e
Moved from "app/src" to "app/application".
Otherwise phpstorm doesn't understand the paths correctly. He thinks that this is not a complete application, but a package. And when creating a class, the namespace indicates “app” with a small letter, but should be “App”.
2024-04-11 19:52:37 +05:00

66 lines
2.1 KiB
PHP

<?php declare(strict_types=1);
namespace App\Services\Storage;
use app\Dto\Service\Storage\Upload;
use App\Models\Storage;
use App\Models\User;
use App\ServiceResults\ServiceResultError;
use App\ServiceResults\Storage\UploadResult;
use App\Services\Service;
use App\Services\Storage\Image\ResizeCommandHandler;
use Illuminate\Support\Facades\DB;
final class ImageService extends Service
{
public function __construct(
private readonly StorageCommandHandler $storageCommandHandler,
private readonly ResizeCommandHandler $resizeCommandHandler,
private readonly int $maxImageWidth,
private readonly int $maxImageHeight,
) { }
public function uploadAndResize(Upload $upload, User $user): ServiceResultError | UploadResult
{
if ($user->cannot('upload', $upload->getMorph()->getPathModel())) {
return $this->errFobidden(__('Access is denied'));
}
if ($upload->getStorageType()->isImage() !== true) {
return $this->errValidate(__('storage.Trying to upload a wrong image'));
}
try {
$storage = DB::transaction(function () use ($upload, $user) {
$storage = $this->storageCommandHandler->handleStore(
upload: $upload,
user: $user,
);
return $this->imageResize($storage, $this->maxImageWidth, $this->maxImageHeight);
});
} catch (\Throwable $e) {
report($e);
return $this->errService(__('Server Error'));
}
return new UploadResult($storage);
}
private function imageResize(Storage $storage, ?int $width, ?int $height): Storage
{
if (empty($width) && empty($height)) {
return $storage;
}
if (!empty($width) && !empty($height)) {
return $this->resizeCommandHandler->resize($storage, $width, $height);
}
if (!empty($height)) {
return $this->resizeCommandHandler->height($storage, $height);
}
return $this->resizeCommandHandler->width($storage, $width);
}
}