You've already forked Epicnabbo-Catalogus-Updated-Daily
89 lines
2.4 KiB
PHP
89 lines
2.4 KiB
PHP
<?php
|
|
namespace App\Services;
|
|
|
|
use App\Models\Miscellaneous\WebsiteSetting;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Throwable;
|
|
|
|
class SettingsService
|
|
{
|
|
/**
|
|
* Store settings as string-to-string collection for type safety.
|
|
* @var Collection<string, string>
|
|
*/
|
|
public private(set) Collection $settings;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->settings = new Collection();
|
|
$this->refresh();
|
|
}
|
|
|
|
/**
|
|
* Get a setting value or return a default.
|
|
*/
|
|
public function getOrDefault(string $settingName, string $default = ''): string
|
|
{
|
|
return $this->settings->get($settingName, $default);
|
|
}
|
|
|
|
/**
|
|
* Refresh settings from database/cache.
|
|
*/
|
|
public function refresh(): void
|
|
{
|
|
Cache::forget('website_settings');
|
|
|
|
try {
|
|
$result = Cache::remember(
|
|
key: 'website_settings',
|
|
ttl: now()->addMinutes(5),
|
|
callback: function () {
|
|
if (!Schema::hasTable('website_settings')) {
|
|
return collect([]);
|
|
}
|
|
return WebsiteSetting::pluck('value', 'key');
|
|
}
|
|
);
|
|
|
|
$data = $this->normalizeSettings($result);
|
|
|
|
/** @var Collection<string, string> */
|
|
$this->settings = new Collection($data);
|
|
} catch (Throwable) {
|
|
/** @var Collection<string, string> */
|
|
$this->settings = new Collection([]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Normalize settings data to ensure all keys and values are strings.
|
|
*
|
|
* @param Collection<array-key, mixed>|array<array-key, mixed> $result
|
|
* @return array<string, string>
|
|
*/
|
|
private function normalizeSettings(Collection|array $result): array
|
|
{
|
|
$data = [];
|
|
|
|
foreach ($result as $key => $value) {
|
|
// array-key is int|string, so we can safely cast to string
|
|
$safeKey = (string) $key;
|
|
|
|
// Ensure value is a string
|
|
if (is_scalar($value)) {
|
|
$safeValue = (string) $value;
|
|
} elseif (is_null($value)) {
|
|
$safeValue = '';
|
|
} else {
|
|
continue; // Skip non-scalar, non-null values
|
|
}
|
|
|
|
$data[$safeKey] = $safeValue;
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
} |