ldc-cocotte/app/Services/ImageOptimizerService.php

86 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Exceptions\ImageOptimizerException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Image;
use Psr\Log\LoggerInterface;
use Shared\Filesystem\TemporaryFileFactory;
final readonly class ImageOptimizerService
{
public const int DEFAULT_QUALITY = 70;
private const array SUPPORTED_MIMES = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'image/avif',
];
public function __construct(
private readonly TemporaryFileFactory $temporaryFileFactory,
private readonly LoggerInterface $logger,
) {
}
/**
* @param int<1, 100> $quality
*/
public function optimize(
UploadedFile $file,
int $quality = self::DEFAULT_QUALITY,
): \SplFileObject {
try {
if (! $this->isImage($file)) {
return $this->toFileObject($file);
}
$bytes = Image::fromUpload($file)
->quality(clamp($quality, 1, 100))
->toBytes();
if ($bytes === false) {
throw new ImageOptimizerException('Could not read image bytes.');
}
return $this->temporaryFileFactory->newWithBytes(
$bytes,
$file->getClientOriginalName()
);
} catch (\Throwable $e) {
$this->logger->warning(
"Image optimization skipped for [{$file->getClientOriginalName()}]: {$e->getMessage()}",
['exception' => $e],
);
return $this->toFileObject($file);
}
}
private function toFileObject(UploadedFile $file): \SplFileObject
{
$bytes = $file->get();
if ($bytes === false) {
throw new ImageOptimizerException('Could not read the uploaded file bytes.');
}
return $this->temporaryFileFactory->newWithBytes($bytes, $file->getClientOriginalName());
}
private function isImage(UploadedFile $file): bool
{
if (! $file->isValid() || ! $file->isReadable()) {
return false;
}
$mime = strtolower((string) $file->getMimeType());
return in_array($mime, self::SUPPORTED_MIMES, true);
}
}