*/ protected $fillable = [ 'page', 'label', 'title', 'subtitle', 'points', 'is_frenchpoultry', 'is_natureeleveurs', 'nutriscore', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'points' => 'array', 'is_frenchpoultry' => 'bool', 'is_natureeleveurs' => 'bool', 'page' => ExpertiseProductPageEnum::class, 'nutriscore' => NutriscoreEnum::class ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); FileStorageHelper::removeOldFile($model, 'picture2'); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); FileStorageHelper::removeFile($model, 'picture2'); }); } // * METHODS /** * Common methods function. * * @param self $model * @return void */ private static function manageFields(self $model): void { self::assertFieldIsUnique('label', $model->label, $model->id); self::assertFieldIsUnique('title', $model->title, $model->id); self::assertNumberOfProductsVip($model->page->value); } /** * Asserts using validation that the label is unique. * * @param string $name * @param mixed $field * @param integer|null $id * @return void */ private static function assertFieldIsUnique(string $name, mixed $field, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, $name, $field, $id); } /** * Asserts the number of products in the specie. * * @param integer $specie * @return void * @throws \Illuminate\Validation\ValidationException If there are more than 3 products. */ private static function assertNumberOfProductsVip(int $specie): void { if (count(self::where('page', '=', $specie)->get()) >= 3) { throw ValidationException::withMessages([ 'Opération impossible, maximum 3 produits peuvent être présents.' ]); } } }