*/ protected $fillable = [ 'title', 'content', 'picture', 'picture_alt', 'picture_title', 'button_display', 'button_text', 'button_url', 'button_newtab', 'published', 'order' ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'button_display' => 'bool', 'button_newtab' => 'bool', 'published' => 'bool', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::setOrder($model); self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); }); static::updating(function (self $model) { self::manageFields($model); }); static::deleting(function (self $model) { self::assertLimitPublishedSections($model, true); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); }); } // * METHODS /** * Common methods function. * * @param self $model * @return void */ private static function manageFields(self $model): void { self::assertLimitPublishedSections($model); ToolboxHelper::assertNoInternalBoUrls('content', $model->content); ToolboxHelper::assertNoInternalBoUrls('button_url', $model->content); $model->content = clean($model->content); $model->picture = FileStorageHelper::storeFile($model, $model->picture); } /** * Set order after the last element of the list. * * @param self $model * @return void */ private static function setOrder(self $model): void { $model->order = \intval(self::query()->max('order')) + 1; } /** * Check if the limit of published element is reached. * * @param self $model * @param boolean $isDeletion * @return void * @throws \Illuminate\Validation\ValidationException Returns if fails. */ private static function assertLimitPublishedSections(self $model, bool $isDeletion = false) { $count = self::query()->where('published', true)->count(); if ( (!$model->published && $count <= 1) || ($model->published && $count >= 5) || ($isDeletion && $count === 1) ) { throw ValidationException::withMessages([ 'Il doit y avoir entre 1 et 5 sections publiées simultanément.' ]); } } }