ldc-loue/app/Models/Slider.php
2022-06-29 14:55:20 +02:00

121 lines
3.5 KiB
PHP

<?php
namespace App\Models;
use App\Casts\RgbaColorNullable;
use App\Enums\Sliders\SliderPosition;
use App\Enums\Sliders\SliderType;
use App\Lib\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Session;
use Kwaadpepper\Enum\Traits\CastsEnums;
class Slider extends Model
{
use CastsEnums;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'title_color',
'title_color_bg',
'subtitle',
'subtitle_color',
'subtitle_color_bg',
'position',
'type',
'picture',
'link',
'link_title',
'link_color',
'link_color_hover',
'link_color_bg',
'link_color_bg_hover',
'link_new_tab',
'status',
'order',
'publish_at',
'unpublish_at'
];
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'position' => SliderPosition::class,
'type' => SliderType::class
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'title_color' => RgbaColorNullable::class,
'title_color_bg' => RgbaColorNullable::class,
'subtitle_color' => RgbaColorNullable::class,
'subtitle_color_bg' => RgbaColorNullable::class,
'link_color' => RgbaColorNullable::class,
'link_color_hover' => RgbaColorNullable::class,
'link_color_bg' => RgbaColorNullable::class,
'link_color_bg_hover' => RgbaColorNullable::class,
'link_new_tab' => 'bool',
'status' => 'bool',
'publish_at' => 'datetime',
'unpublish_at' => 'datetime'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
ToolboxHelper::assertNoInternalBoUrls('link', $model->link);
$model->picture = ToolboxHelper::storeImage($model, $model->picture);
$model->order = self::whereType($model->type)->max('order') ?? 0;
if (!$model->status) {
$model->publish_at = null;
} else {
$model->unpublish_at = null;
}
});
static::updating(function (self $model) {
ToolboxHelper::assertNoInternalBoUrls('link', $model->link);
if ($model->picture != $model->getOriginal('picture')) {
$model->picture = ToolboxHelper::storeImage($model, $model->picture);
}
// * If status changed
if (\boolval($model->getOriginal('status')) !== $model->status) {
if ($model->status) {
$model->publish_at = null;
Session::flash('info', trans('Le slider est à présent publié'));
} else {
$model->unpublish_at = null;
Session::flash('warning', trans('Le slider est à présent dépublié'));
}
}
});
static::updated(function (self $model) {
if ($model->picture != $model->getOriginal('picture')) {
$model->picture = ToolboxHelper::removeOldImage($model, 'picture');
}
});
static::deleting(function (self $model) {
ToolboxHelper::removeImage($model, 'picture');
});
}
// * METHODS
}