diff --git a/src/Fields/Support/AttachableMediaPresenter.php b/src/Fields/Support/AttachableMediaPresenter.php index 31aab6a..6922093 100644 --- a/src/Fields/Support/AttachableMediaPresenter.php +++ b/src/Fields/Support/AttachableMediaPresenter.php @@ -2,16 +2,21 @@ namespace DmitryBubyakin\NovaMedialibraryField\Fields\Support; +use function DmitryBubyakin\NovaMedialibraryField\call_or_default; +use DmitryBubyakin\NovaMedialibraryField\Fields\Medialibrary; use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Support\Str; use Spatie\MediaLibrary\MediaCollections\Models\Media; class AttachableMediaPresenter implements Arrayable { private $media; + private $field; - public function __construct(Media $media) + public function __construct(Media $media, Medialibrary $field) { $this->media = $media; + $this->field = $field; } public function toArray(): array @@ -23,7 +28,22 @@ public function toArray(): array 'fileName' => $this->media->file_name, 'collectionName' => $this->media->collection_name, 'extension' => $this->media->extension, - 'previewUrl' => $this->media->getFullUrl(), + 'previewUrl' => $this->previewUrl(), ]); } + + public function previewUrl(): ?string + { + return transform(call_or_default($this->field->previewCallback, [$this->media], function () { + return Str::is('image/*', $this->media->mime_type) + ? $this->media->getFullUrl() + : null; + }), function (string $url): string { + if ($this->field->appendTimestampToPreview) { + return $url . '?timestamp=' . $this->media->updated_at->getTimestamp(); + } + + return $url; + }); + } } diff --git a/src/Http/Controllers/AttachableController.php b/src/Http/Controllers/AttachableController.php index 1437ccf..5b6da43 100644 --- a/src/Http/Controllers/AttachableController.php +++ b/src/Http/Controllers/AttachableController.php @@ -27,7 +27,9 @@ public function __invoke(MedialibraryRequest $request): JsonResponse return response()->json( $paginator->setCollection( - $paginator->getCollection()->mapInto(AttachableMediaPresenter::class) + $paginator->getCollection()->map( function ($media) use ($field) { + return new AttachableMediaPresenter($media, $field); + }) ) ); }