medialibrary-helper/tests/Models/Post.php

67 lines
2.5 KiB
PHP

<?php
namespace Zoomyboy\MedialibraryHelper\Tests\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Zoomyboy\MedialibraryHelper\Tests\Events\MediaChange;
use Zoomyboy\MedialibraryHelper\Tests\Events\MediaDestroyed;
use Zoomyboy\MedialibraryHelper\Tests\Events\MediaStored;
class Post extends Model implements HasMedia
{
use InteractsWithMedia;
public $guarded = [];
public function registerMediaCollections(): void
{
$this->addMediaCollection('defaultSingleFile')->maxWidth(fn () => 250)->singleFile();
$this->addMediaCollection('conversionsWithDefault')
->singleFile()
->withFallback(fn ($parent) => ['default.jpg', 'public'])
->registerMediaConversions(function () {
$this->addMediaConversion('tiny')->width(200)->height(200);
});
$this->addMediaCollection('images')->after(fn ($model) => Event::dispatch(new MediaChange($model)));
$this->addMediaCollection('singleForced')->singleFile()->forceFileName(function ($model, $name) {
return $name . ' ' . now()->format('Y-m-d');
});
$this->addMediaCollection('multipleForced')->forceFileName(function ($model, $name) {
return $name . ' ' . now()->format('Y-m-d');
});
$this->addMediaCollection('singleStoringHook')->singleFile()->storing(function ($adder, $fileName) {
return $adder->withCustomProperties([
'use' => 'AAA',
'ttt' => pathinfo($fileName, PATHINFO_FILENAME),
]);
});
$this->addMediaCollection('singleWithEvent')->singleFile()->stored(function (Media $media) {
Event::dispatch(new MediaStored($media));
})
->destroyed(fn ($model) => Event::dispatch(new MediaDestroyed($model)))
->after(fn ($model) => Event::dispatch(new MediaChange($model)));
$this->addMediaCollection('multipleFilesWithEvent')->stored(function (Media $media) {
Event::dispatch(new MediaStored($media));
});
$this->addMediaCollection('multipleProperties')->singleFile()->withDefaultProperties(fn ($path, $pathinfo) => [
'test' => Str::camel($path),
])->withPropertyValidation(fn ($path) => [
'test' => 'string|max:10',
])
->after(fn ($model) => Event::dispatch(new MediaChange($model)));
}
}