102 lines
3.1 KiB
PHP
102 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\Helpers\FileStorageHelper;
|
|
use App\Traits\Models\ActivityLog;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
/**
|
|
* @property string $picto Picto path.
|
|
* @property string $picto_title Picto title attribute.
|
|
* @property string $picto_alt Picto alt attribute.
|
|
* @property string $text Legend of picto.
|
|
* @property string $source The origin of the text.
|
|
* @property integer $order Change order request.
|
|
* @property boolean $published Picto publish status.
|
|
* @property-read \Illuminate\Support\Carbon $created_at Created date.
|
|
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
|
|
*/
|
|
class KeyNumber extends Model
|
|
{
|
|
use ActivityLog;
|
|
use HasFactory;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $fillable = [
|
|
'text',
|
|
'picto',
|
|
'picto_alt',
|
|
'picto_title',
|
|
'source',
|
|
'order',
|
|
'published',
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (self $keyNumber) {
|
|
self::setOrder($keyNumber);
|
|
$keyNumber->picto = FileStorageHelper::storeFile($keyNumber, $keyNumber->picto, true);
|
|
});
|
|
static::created(function (self $keyNumber) {
|
|
self::resetCache();
|
|
});
|
|
static::updating(function (self $keyNumber) {
|
|
$keyNumber->picto = FileStorageHelper::storeFile($keyNumber, $keyNumber->picto, true);
|
|
});
|
|
static::updated(function (self $keyNumber) {
|
|
FileStorageHelper::removeOldFile($keyNumber, 'picto');
|
|
self::resetCache();
|
|
});
|
|
static::deleted(function (self $keyNumber) {
|
|
FileStorageHelper::removeFile($keyNumber, 'picto');
|
|
self::resetCache();
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
|
|
/**
|
|
* Reset all cache elements related to this model.
|
|
* @return void
|
|
*/
|
|
private static function resetCache()
|
|
{
|
|
Cache::forget('5publishedKeyNumbersOrderedByOrder');
|
|
self::get5PublishedOrdered();
|
|
}
|
|
|
|
/**
|
|
* Get 5 published key numbers ordered by order.
|
|
* @return \Illuminate\Database\Eloquent\Collection
|
|
*/
|
|
public static function get5PublishedOrdered(): \Illuminate\Database\Eloquent\Collection
|
|
{
|
|
return Cache::rememberForever('5publishedKeyNumbersOrderedByOrder', function () {
|
|
return self::query()->where('published', true)->orderBy('order')->take(5)->get();
|
|
});
|
|
}
|
|
}
|