You've already forked Atomcms-edit
105 lines
2.6 KiB
PHP
Executable File
105 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Miscellaneous\WebsiteLanguage;
|
|
use App\Models\Miscellaneous\WebsiteSetting;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Throwable;
|
|
|
|
class SettingsService
|
|
{
|
|
private const string CACHE_KEY = 'website_settings';
|
|
|
|
private const string LANGUAGES_CACHE_KEY = 'website_languages';
|
|
|
|
private ?Collection $cachedSettings = null;
|
|
|
|
public function __construct(
|
|
private readonly InstallationService $installationService,
|
|
) {}
|
|
|
|
public function getOrDefault(string $key, mixed $default = null): mixed
|
|
{
|
|
$settings = $this->settings();
|
|
|
|
return $settings->get($key, $default);
|
|
}
|
|
|
|
public function getLanguages(): Collection
|
|
{
|
|
return Cache::rememberForever(self::LANGUAGES_CACHE_KEY, function (): Collection {
|
|
try {
|
|
if (! Schema::hasTable('website_languages')) {
|
|
return collect();
|
|
}
|
|
|
|
return WebsiteLanguage::all();
|
|
} catch (Throwable) {
|
|
return collect();
|
|
}
|
|
});
|
|
}
|
|
|
|
public static function clearCache(): void
|
|
{
|
|
Cache::forget(self::CACHE_KEY);
|
|
Cache::forget(self::LANGUAGES_CACHE_KEY);
|
|
}
|
|
|
|
public function clearInstanceCache(): void
|
|
{
|
|
$this->cachedSettings = null;
|
|
Cache::forget(self::CACHE_KEY);
|
|
Cache::forget(self::LANGUAGES_CACHE_KEY);
|
|
}
|
|
|
|
public function set(string $key, mixed $value): void
|
|
{
|
|
WebsiteSetting::updateOrCreate(
|
|
['key' => $key],
|
|
['value' => is_bool($value) ? ($value ? '1' : '0') : (string) $value],
|
|
);
|
|
|
|
// Clear cache to ensure fresh values are fetched
|
|
self::clearCache();
|
|
}
|
|
|
|
private function settings(): Collection
|
|
{
|
|
if ($this->isInstallationIncomplete()) {
|
|
return $this->fetchSettings();
|
|
}
|
|
|
|
$this->cachedSettings = collect(Cache::rememberForever(self::CACHE_KEY, fn () => $this->fetchSettings()->toArray()));
|
|
|
|
return $this->cachedSettings;
|
|
}
|
|
|
|
private function isInstallationIncomplete(): bool
|
|
{
|
|
try {
|
|
return ! $this->installationService->isComplete();
|
|
} catch (Throwable) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private function fetchSettings(): Collection
|
|
{
|
|
try {
|
|
if (! Schema::hasTable('website_settings')) {
|
|
return collect();
|
|
}
|
|
|
|
return WebsiteSetting::query()->pluck('value', 'key');
|
|
} catch (Throwable) {
|
|
return collect();
|
|
}
|
|
}
|
|
}
|