80 lines
1.9 KiB
PHP
80 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Throwable;
|
|
|
|
class Setting extends Model
|
|
{
|
|
protected $primaryKey = 'key';
|
|
|
|
public $incrementing = false;
|
|
|
|
protected $keyType = 'string';
|
|
|
|
protected $fillable = [
|
|
'key',
|
|
'value',
|
|
];
|
|
|
|
/**
|
|
* @var array<string, mixed>|null
|
|
*/
|
|
protected static ?array $runtimeCache = null;
|
|
|
|
public static function flushCache(): void
|
|
{
|
|
static::$runtimeCache = null;
|
|
}
|
|
|
|
public static function get(string $key, mixed $default = null): mixed
|
|
{
|
|
if (static::$runtimeCache === null) {
|
|
try {
|
|
static::$runtimeCache = static::query()->pluck('value', 'key')->all();
|
|
} catch (Throwable) {
|
|
return $default;
|
|
}
|
|
}
|
|
|
|
if (! array_key_exists($key, static::$runtimeCache) || static::$runtimeCache[$key] === null) {
|
|
return $default;
|
|
}
|
|
|
|
$val = static::$runtimeCache[$key];
|
|
|
|
if (is_string($val) && (str_starts_with($val, '{') || str_starts_with($val, '['))) {
|
|
$decoded = json_decode($val, true);
|
|
if (json_last_error() === JSON_ERROR_NONE) {
|
|
return $decoded;
|
|
}
|
|
}
|
|
|
|
return $val;
|
|
}
|
|
|
|
public static function set(string $key, mixed $value): static
|
|
{
|
|
$encoded = is_array($value) || is_object($value) ? json_encode($value) : (string) $value;
|
|
|
|
if (static::$runtimeCache !== null) {
|
|
static::$runtimeCache[$key] = $encoded;
|
|
}
|
|
|
|
return static::query()->updateOrCreate(
|
|
['key' => $key],
|
|
['value' => $encoded]
|
|
);
|
|
}
|
|
|
|
public static function forget(string $key): bool
|
|
{
|
|
if (static::$runtimeCache !== null) {
|
|
unset(static::$runtimeCache[$key]);
|
|
}
|
|
|
|
return (bool) static::query()->where('key', $key)->delete();
|
|
}
|
|
}
|