66 lines
1.6 KiB
PHP
66 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Setting;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
class SettingService
|
|
{
|
|
/**
|
|
* Get a setting value by key, with optional default.
|
|
*/
|
|
public function get(string $key, mixed $default = null): mixed
|
|
{
|
|
// Use cache to prevent repeated DB queries for settings
|
|
$setting = Cache::rememberForever("setting.{$key}", function () use ($key) {
|
|
return Setting::where('key', $key)->first();
|
|
});
|
|
|
|
if (!$setting) {
|
|
return $default;
|
|
}
|
|
|
|
return $setting->getTypedValue();
|
|
}
|
|
|
|
/**
|
|
* Set or update a setting.
|
|
*/
|
|
public function set(string $key, mixed $value, string $type = 'string'): void
|
|
{
|
|
// Convert array/object to json if necessary
|
|
if (is_array($value) || is_object($value)) {
|
|
$value = json_encode($value);
|
|
$type = 'json';
|
|
} elseif (is_bool($value)) {
|
|
$value = $value ? 'true' : 'false';
|
|
$type = 'boolean';
|
|
}
|
|
|
|
Setting::updateOrCreate(
|
|
['key' => $key],
|
|
[
|
|
'value' => (string) $value,
|
|
'type' => $type,
|
|
]
|
|
);
|
|
|
|
// Invalidate cache
|
|
Cache::forget("setting.{$key}");
|
|
}
|
|
|
|
/**
|
|
* Get all settings as an associative array.
|
|
*/
|
|
public function getAll(): array
|
|
{
|
|
$settings = Setting::all();
|
|
$result = [];
|
|
foreach ($settings as $setting) {
|
|
$result[$setting->key] = $setting->getTypedValue();
|
|
}
|
|
return $result;
|
|
}
|
|
}
|