mailwolt/app/Support/SettingsRepository.php

59 lines
1.5 KiB
PHP

<?php
namespace App\Support;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
class SettingsRepository
{
const CACHE_KEY = 'settings.all';
protected function store()
{
// zieht z.B. 'redis' aus .env: CACHE_SETTINGS_STORE=redis
$store = env('CACHE_SETTINGS_STORE', 'redis');
return Cache::store($store);
}
protected function loadAll(): array
{
try {
/** @var array<string,string> $settings */
$settings = $this->store()->rememberForever(self::CACHE_KEY, function (): array {
return Setting::query()
->pluck('value', 'key')
->toArray();
});
return $settings;
} catch (\Throwable $e) {
return Setting::query()->pluck('value', 'key')->toArray();
}
}
public function get(string $key, $default = null)
{
$all = $this->loadAll();
return array_key_exists($key, $all) ? $all[$key] : $default;
}
public function set(string $key, $value): void
{
Setting::query()->updateOrCreate(['key' => $key], ['value' => $value]);
// Cache refreshen
try {
$all = Setting::query()->pluck('value', 'key')->toArray();
$this->store()->forever(self::CACHE_KEY, $all);
} catch (\Throwable $e) {
// Cache kaputt? Ignorieren, DB ist aktualisiert.
}
}
public function forgetCache(): void
{
try { $this->store()->forget(self::CACHE_KEY); } catch (\Throwable $e) {}
}
}