*/ use HasFactory; /** @var integer Minimum number of published slides */ private static int $min = 1; /** @var integer Maximum number of published slides */ private static int $max = 3; /** * The attributes that are mass assignable. * * @var list */ protected $fillable = [ 'type', 'title', 'content', 'video_id', 'button_status', 'button_label', 'button_url', 'button_new_tab', 'picture', 'picture_alt', 'picture_title', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'type' => SliderTypeEnum::class, 'button_status' => 'boolean', 'button_new_tab' => 'boolean', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { if ( $model->type === SliderTypeEnum::team && self::query()->where('type', SliderTypeEnum::team)->count() + 1 > $model::getMaxPublished() ) { throw ValidationException::withMessages([ 'slide' => 'Il ne peut y avoir que 3 slides en même temps.' ]); } self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); }); static::deleting(function (self $model) { if ( $model->type === SliderTypeEnum::team && self::query()->where('type', SliderTypeEnum::team)->count() - 1 < $model::getMinPublished() ) { throw ValidationException::withMessages([ 'slide' => 'Il doit y avoir au mininmum 1 slide d\'active.' ]); } }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); }); } // * METHODS. /** * Manage model fields. * * @param self $model * @return void */ private static function manageFields(self $model): void { $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); } /** * Getter for the $min property. * * @return integer */ public static function getMinPublished(): int { return self::$min; } /** * Getter for the $max property. * * @return integer */ public static function getMaxPublished(): int { return self::$max; } }