63 lines
2.3 KiB
PHP
63 lines
2.3 KiB
PHP
<?php
|
||
|
||
namespace Inhaus\Plugins\Kleinanzeigen;
|
||
|
||
use App\Support\Images;
|
||
use Illuminate\Http\UploadedFile;
|
||
use Illuminate\Support\Facades\Storage;
|
||
use Illuminate\Support\Str;
|
||
use Illuminate\Validation\ValidationException;
|
||
use Inhaus\Plugins\Kleinanzeigen\Models\Listing;
|
||
use Inhaus\Plugins\Kleinanzeigen\Models\ListingImage;
|
||
use Intervention\Image\Drivers\Gd\Driver;
|
||
use Intervention\Image\Encoders\WebpEncoder;
|
||
use Intervention\Image\ImageManager;
|
||
use Throwable;
|
||
|
||
/**
|
||
* Fotos einer Anzeige: verkleinert (max. 1600 px) und als Vorschau (4:3) gespeichert – nicht
|
||
* im öffentlichen Upload-Ordner, sondern nur für angemeldete Personen abrufbar.
|
||
*/
|
||
class Photos
|
||
{
|
||
public const DISK = 'local';
|
||
|
||
public const MAX = 8;
|
||
|
||
public function store(Listing $listing, UploadedFile $file, int $sort): ListingImage
|
||
{
|
||
$base = 'kleinanzeigen/'.$listing->id.'/'.Str::random(24);
|
||
|
||
try {
|
||
return Images::withLocalCopy($file, function (string $local) use ($listing, $base, $sort) {
|
||
Images::raiseMemoryLimitFor($local);
|
||
$manager = ImageManager::usingDriver(Driver::class);
|
||
$image = $manager->decodePath($local)->scaleDown(1600, 1600);
|
||
$disk = Storage::disk(self::DISK);
|
||
$disk->put("{$base}.webp", $image->encode(new WebpEncoder(quality: 82))->toString());
|
||
$width = $image->width();
|
||
$height = $image->height();
|
||
$disk->put("{$base}-thumb.webp", $image->coverDown(640, 480)->encode(new WebpEncoder(quality: 78))->toString());
|
||
|
||
return $listing->images()->create(['path' => "{$base}.webp", 'thumb_path' => "{$base}-thumb.webp", 'width' => $width, 'height' => $height, 'sort' => $sort]);
|
||
});
|
||
} catch (ValidationException $e) {
|
||
throw $e;
|
||
} catch (Throwable $e) {
|
||
report($e);
|
||
|
||
throw ValidationException::withMessages(['images' => "„{$file->getClientOriginalName()}“ ließ sich nicht als Bild lesen."]);
|
||
}
|
||
}
|
||
|
||
public function delete(ListingImage $image): void
|
||
{
|
||
Storage::disk(self::DISK)->delete([$image->path, $image->thumb_path]);
|
||
$image->delete();
|
||
}
|
||
|
||
public function deleteAll(Listing $listing): void
|
||
{
|
||
Storage::disk(self::DISK)->deleteDirectory('kleinanzeigen/'.$listing->id);
|
||
}
|
||
}
|