ldc-ovoteam/app/Services/ImageOptimizerService.php
Jérémy Munsch dea6dc8a63
feat(test): add unit tests for ImageOptimizerService
- Implemented tests to verify the functionality of the ImageOptimizerService.
- Tests cover optimization of supported image formats, handling of unsupported files, and cleanup of temporary files.
- Added functionality to store optimized images onto disk using a storage service.
2026-11-06 08:51:44 +01:00

78 lines
2.1 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;
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 ?LoggerInterface $logger = null,
) {
}
/**
* @param int<1, 100> $quality
*
* @throws ImageOptimizerException If the image could not be optimized.
*/
public function optimize(
UploadedFile $file,
int $quality = self::DEFAULT_QUALITY,
): UploadedFile {
if (! $this->isImage($file)) {
return $file;
}
try {
$image = Image::fromUpload($file)
->quality(clamp($quality, 1, 100));
$tempPath = tempnam(sys_get_temp_dir(), 'opt_');
if ($tempPath === false || file_put_contents($tempPath, $image->toBytes()) === false) {
throw new ImageOptimizerException('Could not persist optimized image to temporary disk.');
}
return new AutoCleanupUploadedFile(
path: $tempPath,
originalName: $file->getClientOriginalName(),
mimeType: $file->getMimeType() ?? 'image/jpeg',
error: UPLOAD_ERR_OK,
test: true,
);
} catch (\Throwable $e) {
$this->logger?->warning(
"Image optimization skipped for [{$file->getClientOriginalName()}]: {$e->getMessage()}",
['exception' => $e],
);
return $file;
}
}
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);
}
}