Feature: Updating Product Service to handle multiple locales, fetching the correct locale, or, the default locale as fallback

This commit is contained in:
2026-08-26 23:52:33 +03:00
parent ef9e9daab0
commit 0edf7b156d
5 changed files with 115 additions and 35 deletions
@@ -0,0 +1,34 @@
<?php
namespace Modules\Core\Catalog;
use Filament\Forms\Components\Component;
/**
* A Product Option Type describes how a category of Lunar `ProductOption` (e.g.
* "Color", "Size", "Material") behaves — namely, what structured data its values
* carry in their free-form `meta` jsonb column, and how an admin edits that data.
*
* `ProductOption`/`ProductOptionValue` themselves stay exactly as Lunar defines
* them — this is not a new model, just a registry (ProductOptionTypeRegistry) that
* maps a `ProductOption::handle` to the type describing it, so adding a new kind of
* option (a new color-like or size-like concept) is a single new class, not scattered
* per-option special-casing across the admin UI or storefront.
*/
interface ProductOptionTypeInterface
{
/**
* Matches the ProductOption::handle this type describes (e.g. 'color', 'size').
*/
public static function getKey(): string;
/**
* Filament form components for editing a ProductOptionValue's `meta` under this
* option type — e.g. Color returns a color picker for `meta.hex`, Size returns a
* numeric input for `meta.sort_value`. Field names should be dot-notation under
* `meta` (e.g. `meta.hex`), matching where ValuesRelationManager's form saves them.
*
* @return array<Component>
*/
public function getMetaForm(): array;
}
+16 -6
View File
@@ -6,7 +6,7 @@ use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Lunar\Models\Product;
use Modules\Core\Localization\LocaleMiddleware;
use Modules\Core\Localization\Services\LanguageCache;
/**
* Storefront product listing/filtering AND single-product lookup, all reading directly
@@ -19,6 +19,8 @@ use Modules\Core\Localization\LocaleMiddleware;
*/
class ProductService
{
public function __construct(private readonly LanguageCache $languages) {}
/**
* @return array{data: array<int, array>, meta: array}
*/
@@ -80,10 +82,14 @@ class ProductService
/**
* Resolves the current-locale `name`/`description` from the indexer's
* per-locale `name_{locale}`/`description_{locale}` fields, falling back to
* the store's default language (Language::default, see
* LocaleMiddleware::defaultLocale()) when the current locale has no
* translation - e.g. a product with no English copy yet still shows its
* Greek name/description on /en/ rather than rendering blank.
* the store's default language (LanguageCache::defaultLocale()) when the
* current locale has no translation - e.g. a product with no English copy
* yet still shows its Greek name/description on /en/ rather than rendering
* blank. The raw per-locale keys are then stripped - every configured
* locale's translation is indexed in Meilisearch (Lunar's base indexer
* explodes every TranslatedText attribute into name_{locale}/
* description_{locale} per store language), but once resolved into `name`/
* `description`, callers only ever need the one that matched.
*
* Deliberately not config('app.locale') - App::setLocale() overwrites that
* config value on every request, so by request time it's just whatever the
@@ -92,11 +98,15 @@ class ProductService
private function withLocalizedFields(array $product): array
{
$locale = App::getLocale();
$fallbackLocale = LocaleMiddleware::defaultLocale();
$fallbackLocale = $this->languages->defaultLocale();
$product['name'] = $product['name_'.$locale] ?? $product['name_'.$fallbackLocale] ?? null;
$product['description'] = $product['description_'.$locale] ?? $product['description_'.$fallbackLocale] ?? null;
foreach ($this->languages->availableLocales() as $availableLocale) {
unset($product['name_'.$availableLocale], $product['description_'.$availableLocale]);
}
return $product;
}
@@ -5,12 +5,14 @@ namespace Modules\Core\Localization\Listeners;
use Modules\Core\Localization\Events\LanguageCreated;
use Modules\Core\Localization\Events\LanguageDeleted;
use Modules\Core\Localization\Events\LanguageUpdated;
use Modules\Core\Localization\LocaleMiddleware;
use Modules\Core\Localization\Services\LanguageCache;
class FlushLanguageCache
{
public function __construct(private readonly LanguageCache $languages) {}
public function handle(LanguageCreated|LanguageUpdated|LanguageDeleted $event): void
{
LocaleMiddleware::forgetLanguagesCache();
$this->languages->forget();
}
}
+3 -27
View File
@@ -6,19 +6,19 @@ use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Lunar\Models\Language;
use Modules\Core\Localization\Services\LanguageCache;
use Symfony\Component\HttpFoundation\Response;
class LocaleMiddleware
{
private const CACHE_KEY = 'core.localization.languages';
public function __construct(private readonly LanguageCache $languages) {}
public function handle(Request $request, Closure $next): Response
{
$languages = $this->availableLanguages();
$languages = $this->languages->all();
if ($languages->isEmpty()) {
return $next($request);
@@ -45,22 +45,6 @@ class LocaleMiddleware
return $next($request);
}
public static function forgetLanguagesCache(): void
{
Cache::forget(self::CACHE_KEY);
}
/**
* The store's default language code (e.g. 'el') - the fixed fallback other
* locale-aware code (Modules\Core\Catalog\ProductService) should use, as
* opposed to config('app.locale') which App::setLocale() mutates per
* request and so can't serve as a stable fallback.
*/
public static function defaultLocale(): ?string
{
return (new self)->availableLanguages()->firstWhere('default', true)?->code;
}
/**
* Shares the current locale and every OTHER available locale (each with its
* own URL for the current page) with all views, so the header language
@@ -120,12 +104,4 @@ class LocaleMiddleware
return $languages->firstWhere('default', true)?->code
?? $languages->first()->code;
}
private function availableLanguages(): Collection
{
return Cache::rememberForever(
self::CACHE_KEY,
fn () => Language::query()->get(['id', 'code', 'name', 'default']),
);
}
}
@@ -0,0 +1,58 @@
<?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
* Modules\Core\Localization\LocaleMiddleware (request-time locale resolution) and
* any other locale-aware code (e.g. Modules\Core\Catalog\ProductService) read
* 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
* Modules\Core\Catalog\ProductService::withLocalizedFields()), rather than
* 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);
}
}