Files
laravel-manager-packagist/src/Modules/Media/MediaLibrary.php
T

123 lines
4.2 KiB
PHP

<?php
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Support\MediaUsage;
/**
* The one place that knows where media files physically are. Everything else works with Media
* rows and their URLs. New uploads go to the disk in config('manager.media.disk'); an existing
* file is always read from and deleted on the disk its own row names.
*/
class MediaLibrary
{
public function __construct(private readonly MediaUsage $usage) {}
/** @throws MediaStorageException */
public function store(UploadedFile $file, ?Authenticatable $uploader = null, ?string $disk = null): Media
{
$extension = strtolower($file->getClientOriginalExtension());
$baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : '');
$path = $file->getRealPath();
if ($path === false) {
throw new MediaStorageException('The uploaded file could not be read.');
}
$mimeType = $file->getMimeType() ?? 'application/octet-stream';
$dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false;
$disk ??= config('manager.media.disk');
$location = $file->store('media/'.now()->format('Y/m'), $disk);
if ($location === false) {
throw new MediaStorageException('The file could not be stored.');
}
return Media::create([
'disk' => $disk,
'location' => $location,
'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''),
'filename' => $filename,
'mime_type' => $mimeType,
'size' => (int) $file->getSize(),
'checksum' => hash_file('sha256', $path) ?: null,
'width' => $dimensions !== false ? $dimensions[0] : null,
'height' => $dimensions !== false ? $dimensions[1] : null,
'uploaded_by' => $uploader?->getAuthIdentifier(),
]);
}
/**
* How full the library is: what all files together take, how much it may hold
* (`manager.media.max_total_gb`) and what is left. In bytes.
*
* @return array{used: int, limit: int, left: int}
*/
public function room(): array
{
$configured = config('manager.media.max_total_gb');
$limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000);
$used = (int) Media::query()->sum('size');
return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)];
}
/**
* Open a file's content as a stream. Read it and close it.
*
* @return resource
*
* @throws MediaStorageException with status 404 when the file is gone
*/
public function open(Media $media)
{
$stream = Storage::disk($media->disk)->readStream($media->location);
if (! is_resource($stream)) {
throw new MediaStorageException('The file is no longer there.', 404);
}
return $stream;
}
/** Delete the file and then its row. When the storage refuses, the row stays. */
public function delete(Media $media): void
{
$disk = Storage::disk($media->disk);
if ($disk->exists($media->location) && ! $disk->delete($media->location)) {
throw new MediaStorageException('The file could not be deleted.');
}
$media->delete();
}
/**
* How often each media file is used, keyed by media id: how many of the registered sources
* (MediaUsage) hold its address. Nothing registered means 0.
*
* @param iterable<Media> $items
* @return array<int, int>
*/
public function usageCounts(iterable $items): array
{
$haystacks = $this->usage->haystacks();
$counts = [];
foreach ($items as $media) {
$prefix = $media->urlPrefix();
$counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix)));
}
return $counts;
}
}