¨4.0.1¨
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Media\Eloquent;
|
||||
|
||||
use Modules\Media\Entities\File;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphToMany;
|
||||
|
||||
trait HasMedia
|
||||
{
|
||||
@@ -11,42 +12,24 @@ trait HasMedia
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function bootHasMedia()
|
||||
public static function bootHasMedia(): void
|
||||
{
|
||||
static::saved(function ($entity) {
|
||||
$entity->syncFiles(request('files', []));
|
||||
if (method_exists($entity, 'extractMediaFromRequest')) {
|
||||
$entity->syncFiles($entity->extractMediaFromRequest() ?? []);
|
||||
} else {
|
||||
$entity->syncFiles(request('files', []));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all of the files for the entity.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
|
||||
*/
|
||||
public function files()
|
||||
{
|
||||
return $this->morphToMany(File::class, 'entity', 'entity_files')
|
||||
->withPivot(['id', 'zone'])
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter files by zone.
|
||||
*
|
||||
* @param string $zone
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
*/
|
||||
public function filterFiles($zone)
|
||||
{
|
||||
return $this->files()->wherePivot('zone', $zone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync files for the entity.
|
||||
*
|
||||
* @param array $files
|
||||
*/
|
||||
public function syncFiles($files = [])
|
||||
public function syncFiles(array $files = []): void
|
||||
{
|
||||
$entityType = get_class($this);
|
||||
|
||||
@@ -54,7 +37,7 @@ trait HasMedia
|
||||
$syncList = [];
|
||||
|
||||
foreach (array_wrap($fileIds) as $fileId) {
|
||||
if (! empty($fileId)) {
|
||||
if (!empty($fileId)) {
|
||||
$syncList[$fileId]['zone'] = $zone;
|
||||
$syncList[$fileId]['entity_type'] = $entityType;
|
||||
}
|
||||
@@ -64,4 +47,30 @@ trait HasMedia
|
||||
$this->filterFiles($zone)->attach($syncList);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Filter files by zone.
|
||||
*
|
||||
* @param string $zone
|
||||
*
|
||||
* @return MorphToMany
|
||||
*/
|
||||
public function filterFiles(string|array $zones): MorphToMany
|
||||
{
|
||||
return $this->files()->wherePivotIn('zone', array_wrap($zones));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get all the files for the entity.
|
||||
*
|
||||
* @return MorphToMany
|
||||
*/
|
||||
public function files(): MorphToMany
|
||||
{
|
||||
return $this->morphToMany(File::class, 'entity', 'entity_files')
|
||||
->withPivot(['id', 'zone'])
|
||||
->withTimestamps();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user