50 lines
1.8 KiB
PHP
50 lines
1.8 KiB
PHP
<?php
|
|
namespace App\Services;
|
|
|
|
use App\Services\ThumbnailService;
|
|
|
|
class ThumbnailPresenter
|
|
{
|
|
/**
|
|
* Present thumbnail data for an item which may be a model or an array.
|
|
* Returns ['id' => int|null, 'title' => string, 'url' => string, 'srcset' => string|null]
|
|
*/
|
|
public static function present($item, string $size = 'md'): array
|
|
{
|
|
$uext = 'jpg';
|
|
$isEloquent = $item instanceof \Illuminate\Database\Eloquent\Model;
|
|
|
|
$id = null;
|
|
$title = '';
|
|
|
|
if ($isEloquent) {
|
|
$id = $item->id ?? null;
|
|
$title = $item->name ?? '';
|
|
$url = $item->thumb_url ?? $item->thumb ?? '';
|
|
$srcset = $item->thumb_srcset ?? null;
|
|
return ['id' => $id, 'title' => $title, 'url' => $url, 'srcset' => $srcset];
|
|
}
|
|
|
|
// If it's an object but not an Eloquent model (e.g. stdClass row), cast to array
|
|
if (is_object($item)) {
|
|
$item = (array) $item;
|
|
}
|
|
|
|
$id = $item['id'] ?? null;
|
|
$title = $item['name'] ?? '';
|
|
|
|
// If array contains direct hash/thumb_ext, use CDN fromHash
|
|
$hash = $item['hash'] ?? null;
|
|
$thumbExt = $item['thumb_ext'] ?? ($item['ext'] ?? $uext);
|
|
if (!empty($hash) && !empty($thumbExt)) {
|
|
$url = ThumbnailService::fromHash($hash, $thumbExt, $size) ?: ThumbnailService::url(null, $id, $thumbExt, 6);
|
|
$srcset = ThumbnailService::srcsetFromHash($hash, $thumbExt);
|
|
return ['id' => $id, 'title' => $title, 'url' => $url, 'srcset' => $srcset];
|
|
}
|
|
|
|
// Fallback: ask ThumbnailService to resolve by id or file path
|
|
$url = ThumbnailService::url(null, $id, $uext, 6);
|
|
return ['id' => $id, 'title' => $title, 'url' => $url, 'srcset' => null];
|
|
}
|
|
}
|