ldc-volena/app/Models/Carousel.php

117 lines
3.2 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property-read int $id Id.
* @property string $title Title.
* @property array $media Medias of the carousel.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
*
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/
class Carousel extends Model
{
use ActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'section_id',
'title',
'media',
'order',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'media' => 'array',
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
$otherCarousels = self::query()
->whereRelation('section', 'id', $model->section->id)
->count();
if ($otherCarousels > 4) {
throw new \RuntimeException('Creating more than 5 carousels is not allowed');
}
self::setOrder($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFiles(
data_get(ToolboxHelper::getOriginal($model, 'media'), 'pictures.*.path', ['']),
data_get($model->media, 'pictures.*.path', [''])
);
});
static::deleted(function (self $model) {
FileStorageHelper::removeOldFiles(
data_get($model->media, 'pictures.*.path', ['']),
['']
);
self::setOrder($model, true);
});
}
// * METHODS
/**
* Set order after the last element of the list.
*
* @param self $model
* @param boolean $isDeletion
* @return void
*/
private static function setOrder(self $model, bool $isDeletion = false): void
{
$maxOrder = \intval(self::query()->where('section_id', $model->section_id)->max('order'));
if ($isDeletion) {
$request = Carousel::query()
->where('section_id', $model->section_id)
->whereNot('id', $model->id)
->whereBetween('order', [$model->order, $maxOrder]);
$request->decrement('order', 1);
return;
}
$model->order = $maxOrder + 1;
}
// * RELATIONSHIPS
/**
* Get the sections that owns the Carousel
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function section(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Section::class);
}
}