2026-08-26 23:52:33 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Modules\Core\Localization\Services;
|
|
|
|
|
|
|
|
|
|
use Illuminate\Support\Collection;
|
|
|
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
|
use Lunar\Models\Language;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Cached read layer over Lunar's `languages` table — the single source both
|
2026-08-27 01:08:34 +03:00
|
|
|
* Modules\Core\Localization\Middleware\LocaleMiddleware (request-time locale resolution) and
|
2026-08-27 01:05:04 +03:00
|
|
|
* any other locale-aware code (e.g. Modules\Core\Product\Services\ProductService) read
|
2026-08-26 23:52:33 +03:00
|
|
|
* from, so the language list is fetched once per cache lifetime rather than once
|
|
|
|
|
* per caller. Cached forever, invalidated via forget() by
|
|
|
|
|
* Modules\Core\Localization\Listeners\FlushLanguageCache on
|
|
|
|
|
* LanguageCreated/LanguageUpdated/LanguageDeleted.
|
|
|
|
|
*/
|
|
|
|
|
class LanguageCache
|
|
|
|
|
{
|
|
|
|
|
private const CACHE_KEY = 'core.localization.languages';
|
|
|
|
|
|
|
|
|
|
public function all(): Collection
|
|
|
|
|
{
|
|
|
|
|
return Cache::rememberForever(
|
|
|
|
|
self::CACHE_KEY,
|
|
|
|
|
fn () => Language::query()->get(['id', 'code', 'name', 'default']),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The store's default language code (e.g. 'el') - the fixed fallback other
|
|
|
|
|
* locale-aware code should use, as opposed to config('app.locale') which
|
|
|
|
|
* App::setLocale() mutates per request and so can't serve as a stable
|
|
|
|
|
* fallback.
|
|
|
|
|
*/
|
|
|
|
|
public function defaultLocale(): ?string
|
|
|
|
|
{
|
|
|
|
|
return $this->all()->firstWhere('default', true)?->code;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Every configured store locale code (e.g. ['el', 'en']) - for code that needs
|
|
|
|
|
* to enumerate all locales a TranslatedText attribute was indexed under (see
|
2026-08-27 01:05:04 +03:00
|
|
|
* Modules\Core\Product\Services\ProductService::withLocalizedFields()), rather than
|
2026-08-26 23:52:33 +03:00
|
|
|
* hardcoding locale codes.
|
|
|
|
|
*
|
|
|
|
|
* @return array<int, string>
|
|
|
|
|
*/
|
|
|
|
|
public function availableLocales(): array
|
|
|
|
|
{
|
|
|
|
|
return $this->all()->pluck('code')->all();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function forget(): void
|
|
|
|
|
{
|
|
|
|
|
Cache::forget(self::CACHE_KEY);
|
|
|
|
|
}
|
|
|
|
|
}
|