ldc-legaulois/app/Models/GeneralConfig.php

117 lines
2.7 KiB
PHP
Raw Normal View History

2021-09-20 16:19:42 +02:00
<?php
namespace App\Models;
use App\Enums\GeneralConfigType;
use App\Traits\MiniCrudModel;
2022-05-31 16:44:41 +02:00
use Illuminate\Database\Eloquent\Collection;
2021-09-20 16:19:42 +02:00
use Illuminate\Database\Eloquent\Model;
2021-09-20 23:23:46 +02:00
use Illuminate\Support\Facades\Cache;
2021-09-20 16:19:42 +02:00
use Kwaadpepper\Enum\Traits\CastsEnums;
class GeneralConfig extends Model
{
use CastsEnums;
use MiniCrudModel;
2022-05-31 16:44:41 +02:00
/**
* The primary key for the model.
*
* @var string
*/
2021-09-20 16:19:42 +02:00
protected $primaryKey = 'type';
2022-05-31 16:44:41 +02:00
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
2021-09-20 16:19:42 +02:00
public $incrementing = false;
2022-05-31 16:44:41 +02:00
/**
* The attributes that are mass assignable.
*
* @var array
*/
2021-09-20 16:19:42 +02:00
protected $fillable = [
'type', 'data'
];
2021-09-20 23:23:46 +02:00
2022-05-31 16:44:41 +02:00
/**
* 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
*/
2021-09-20 23:23:46 +02:00
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');
});
}
2022-05-31 16:44:41 +02:00
/**
* Get all cached configs
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getCachedConfigs(): Collection
2021-09-20 23:23:46 +02:00
{
if (!Cache::has('GeneralConfigGlobal')) {
self::setCachedConfigs();
}
return Cache::get('GeneralConfigGlobal');
}
2022-05-31 16:44:41 +02:00
/**
* Put configs into cache
*
* @return void
*/
2021-09-20 23:23:46 +02:00
protected static function setCachedConfigs()
{
$configs = GeneralConfig::all();
Cache::put('GeneralConfigGlobal', $configs);
}
2022-05-31 16:44:41 +02:00
/**
* 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);
});
}
2021-09-20 16:19:42 +02:00
}