ldc-volena/app/Models/Brand.php
2026-04-24 15:06:55 +02:00

119 lines
3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class Brand extends Model
{
use ActivityLog;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'text',
'picture',
'picture_alt',
'picture_title',
'link',
'published',
'aisle_id'
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'published' => 'bool',
];
/**
* 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');
});
static::deleting(function (self $model) {
self::assertLimitPublishedModels($model, true);
});
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
{
// * ASSERTIONS.
self::assertLimitPublishedModels($model);
// * TRANSFORMATIONS.
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
/**
* Check if the limit of published models is reached.
*
* @param self $model
* @param boolean $isDeletion
* @throws \Illuminate\Validation\ValidationException If the limit of published models is reached.
* @return void
*/
private static function assertLimitPublishedModels(self $model, bool $isDeletion = false)
{
$count = self::query()
->where('published', true)
->where('aisle_id', $model->aisle_id)
->count();
$updatePublished = !$isDeletion && $model->published && !$model->getOriginal('published');
if (
$count !== 0 &&
((!$model->published && $count <= 1) ||
($updatePublished && $count >= 5) ||
($isDeletion && $count === 1))
) {
throw ValidationException::withMessages([
'Il doit y avoir entre 1 et 5 éléments publiés simultanément.'
]);
}
}
// * RELATIONS.
/**
* Associated aisle.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Aisle,$this>
*/
public function aisle(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Aisle::class);
}
}