ldc-legaulois/app/Models/GeneralConfig.php
2022-05-31 17:13:19 +02:00

116 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use App\Enums\GeneralConfigType;
use App\Traits\MiniCrudModel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Kwaadpepper\Enum\Traits\CastsEnums;
class GeneralConfig extends Model
{
use CastsEnums;
use MiniCrudModel;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'type';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'type', 'data'
];
/**
* The attributes that should be cast to Enums.
*
* @var array
*/
protected $enumCasts = [
'type' => GeneralConfigType::class
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'data' => 'array'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
static::created(function (GeneralConfig $config) {
Cache::delete('GeneralConfigGlobal');
});
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
static::updated(function (GeneralConfig $config) {
Cache::delete('GeneralConfigGlobal');
});
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
static::deleted(function (GeneralConfig $config) {
Cache::delete('GeneralConfigGlobal');
});
}
/**
* Get all cached configs
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getCachedConfigs(): Collection
{
if (!Cache::has('GeneralConfigGlobal')) {
self::setCachedConfigs();
}
return Cache::get('GeneralConfigGlobal');
}
/**
* Put configs into cache
*
* @return void
*/
protected static function setCachedConfigs()
{
$configs = GeneralConfig::all();
Cache::put('GeneralConfigGlobal', $configs);
}
/**
* Get specific config,
* Every config is mandatory
*
* @param GeneralConfigType $type
* @return GeneralConfig
*/
public static function getCachedConfig(GeneralConfigType $type): GeneralConfig
{
return self::getCachedConfigs()->first(function (GeneralConfig $config) use ($type) {
return $config->type->equals($type);
});
}
}