clusev/app/Models/Setting.php

53 lines
1.6 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
/**
* Dashboard-configurable key/value settings (release channel, dashboard domain,
* TLS email, …). Cached per key; cache is busted on write.
*/
class Setting extends Model
{
protected $primaryKey = 'key';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
public static function get(string $key, ?string $default = null): ?string
{
$value = Cache::rememberForever("setting:{$key}", fn () => static::query()->find($key)?->value);
return $value ?? $default;
}
/**
* Read a setting DIRECTLY from the DB, bypassing the read-through cache. For SECURITY-SENSITIVE
* values (e.g. an alert token) where a concurrent cache-miss could re-populate a STALE value just
* after a change and pair an old secret with a new target — the cache-aside race the plain get()
* is exposed to. Costs one query; use only where staleness is a correctness/security bug.
*/
public static function uncached(string $key, ?string $default = null): ?string
{
return static::query()->find($key)?->value ?? $default;
}
public static function put(string $key, ?string $value): void
{
static::query()->updateOrCreate(['key' => $key], ['value' => $value]);
Cache::forget("setting:{$key}");
}
/** Remove a setting entirely (so get() falls back to its default). */
public static function forget(string $key): void
{
static::query()->whereKey($key)->delete();
Cache::forget("setting:{$key}");
}
}