Upload beautify

This commit is contained in:
2026-02-14 15:14:12 +01:00
parent e129618910
commit 79192345e3
249 changed files with 24436 additions and 1021 deletions

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Services\Uploads;
use Illuminate\Support\Facades\File;
use Intervention\Image\ImageManager as ImageManager;
use Intervention\Image\Interfaces\ImageInterface as InterventionImageInterface;
use RuntimeException;
final class UploadDerivativesService
{
private bool $imageAvailable = false;
private ?ImageManager $manager = null;
public function __construct(private readonly UploadStorageService $storage)
{
// Intervention Image v3 uses ImageManager; instantiate appropriate driver
try {
$this->manager = extension_loaded('gd') ? ImageManager::gd() : ImageManager::imagick();
$this->imageAvailable = true;
} catch (\Throwable $e) {
logger()->warning('Intervention Image present but configuration failed: ' . $e->getMessage());
$this->imageAvailable = false;
$this->manager = null;
}
}
public function storeOriginal(string $sourcePath, string $hash): string
{
$this->assertImageAvailable();
$dir = $this->storage->ensureHashDirectory('originals', $hash);
$target = $dir . DIRECTORY_SEPARATOR . 'orig.webp';
$quality = (int) config('uploads.quality', 85);
/** @var InterventionImageInterface $img */
$img = $this->manager->read($sourcePath);
$encoder = new \Intervention\Image\Encoders\WebpEncoder($quality);
$encoded = (string) $img->encode($encoder);
File::put($target, $encoded);
return $target;
}
public function generatePublicDerivatives(string $sourcePath, string $hash): array
{
$this->assertImageAvailable();
$quality = (int) config('uploads.quality', 85);
$variants = (array) config('uploads.derivatives', []);
$dir = $this->storage->publicHashDirectory($hash);
$written = [];
foreach ($variants as $variant => $options) {
$variant = (string) $variant;
$path = $dir . DIRECTORY_SEPARATOR . $variant . '.webp';
/** @var InterventionImageInterface $img */
$img = $this->manager->read($sourcePath);
if (isset($options['size'])) {
$size = (int) $options['size'];
$out = $img->cover($size, $size);
} else {
$max = (int) ($options['max'] ?? 0);
if ($max <= 0) {
$max = 2560;
}
$out = $img->scaleDown($max, $max);
}
$encoder = new \Intervention\Image\Encoders\WebpEncoder($quality);
$encoded = (string) $out->encode($encoder);
File::put($path, $encoded);
$written[$variant] = $path;
}
return $written;
}
private function assertImageAvailable(): void
{
if (! $this->imageAvailable) {
throw new RuntimeException('Intervention Image is not available.');
}
}
}