ldc-gen-game-web/app/Models/Product.php
noah.lancien 218a3a7891 phpstan
2024-01-31 09:03:18 +00:00

106 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Traits\Models\IsCachedAsCollection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Product.
*
* @property string $name Name
* @property string $picture Path of the picture
* @property string $picture_alt Alt text for the picture
* @property string $picture_title Title text for the picture
* @property integer $ean_code Ean code
* @property-read \Illuminate\Support\Carbon $created_at Creation Date.
* @property-read \Illuminate\Support\Carbon $updated_at Last update Date.
*
* @property-read \App\Models\Range[] $range Associated range.
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Participation[] $participations
* Associated participations.
*/
class Product extends Model
{
use HasFactory;
use IsCachedAsCollection;
/**
* The attributes that are mass assignable.
*
* @var array<string>
*/
protected $fillable = [
'name',
'picture',
'picture_alt',
'picture_title',
'ean_code',
'range_id',
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::created(fn () => self::removeCached());
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
self::removeCached();
FileStorageHelper::removeOldFile($model, 'picture');
});
static::deleted(function (self $model) {
self::removeCached();
FileStorageHelper::removeFile($model, 'picture');
});
}
// * METHODS
/**
* Common methods function.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model)
{
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
// * RELATIONSHIPS
/**
* Range relation
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function range(): BelongsTo
{
return $this->belongsTo(Range::class);
}
/**
* Participations relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function participations(): HasMany
{
return $this->hasMany(Participation::class);
}
}