diff --git a/Updated_Cms/app/Services/SettingsService.php b/Updated_Cms/app/Services/SettingsService.php index de2e21d86b..1b1d41e779 100644 --- a/Updated_Cms/app/Services/SettingsService.php +++ b/Updated_Cms/app/Services/SettingsService.php @@ -1,5 +1,4 @@ */ + /** + * Store settings as string-to-string collection for type safety. + * @var Collection + */ public private(set) Collection $settings; public function __construct() { + $this->settings = new Collection(); $this->refresh(); } - public function getOrDefault(string $settingName, ?string $default = null): string + /** + * Get a setting value or return a default. + */ + public function getOrDefault(string $settingName, string $default = ''): string { - return (string) $this->settings->get($settingName, $default); + return $this->settings->get($settingName, $default); } + /** + * Refresh settings from database/cache. + */ public function refresh(): void { Cache::forget('website_settings'); - + try { - /** @var mixed $result */ $result = Cache::remember( key: 'website_settings', ttl: now()->addMinutes(5), - callback: fn () => Schema::hasTable('website_settings') - ? WebsiteSetting::pluck('value', 'key') - : collect() + callback: function () { + if (!Schema::hasTable('website_settings')) { + return collect([]); + } + return WebsiteSetting::pluck('value', 'key'); + } ); - /** @var array $data */ - $data = []; - - if ($result instanceof Collection) { - foreach ($result as $key => $value) { - $data[(string) $key] = is_scalar($value) ? (string) $value : ''; - } - } elseif (is_array($result)) { - foreach ($result as $key => $value) { - $data[(string) $key] = is_scalar($value) ? (string) $value : ''; - } - } - + $data = $this->normalizeSettings($result); + + /** @var Collection */ $this->settings = new Collection($data); } catch (Throwable) { - $this->settings = new Collection(); + /** @var Collection */ + $this->settings = new Collection([]); } } -} + + /** + * Normalize settings data to ensure all keys and values are strings. + * + * @param Collection|array $result + * @return array + */ + 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; + } +} \ No newline at end of file