Skip to content

Commit edaa984

Browse files
committed
feat: add locale_names and available_locales helpers
Add two new helper functions: - locale_names($page): returns locale code => display name map, with support for site-level overrides via the localeNames config key. - available_locales($page): returns url key => display name map for all active locales, mapping the default locale to an empty key. These helpers allow sites to remove the localeNames config array and the locales closure from their config.php, keeping that logic here. Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com>
1 parent c6766c3 commit edaa984

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

src/helpers.php

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,54 @@ function packageDefaultLocale($page = null): string
117117
{
118118
return $page->defaultLocale ?? 'en';
119119
}
120+
121+
/**
122+
* Returns the display name map for all supported locales.
123+
* Falls back to the locale code if not found.
124+
*
125+
* Site-level overrides can be provided via a `localeNames` config key.
126+
*
127+
* @param mixed $page
128+
* @return array<string, string> locale code => display name
129+
*/
130+
function locale_names($page): array
131+
{
132+
static $defaults = [
133+
'en' => 'English',
134+
'cs' => 'Čeština',
135+
'fr' => 'Français',
136+
'nb-NO' => 'Norsk bokmål',
137+
'pt' => 'Português',
138+
'pt-BR' => 'Português Brasil',
139+
'ta' => 'தமிழ்',
140+
];
141+
142+
if (isset($page->localeNames) && is_array($page->localeNames)) {
143+
return $page->localeNames;
144+
}
145+
146+
return $defaults;
147+
}
148+
149+
/**
150+
* Returns an ordered map of URL key => display name for all available locales.
151+
* The default locale uses an empty string key (no URL prefix).
152+
*
153+
* Intended for use in navigation language selectors.
154+
*
155+
* @param mixed $page
156+
* @return array<string, string> url key => display name
157+
*/
158+
function available_locales($page): array
159+
{
160+
$names = locale_names($page);
161+
162+
return $page->localization->keys()
163+
->mapWithKeys(function ($locale) use ($page, $names) {
164+
$urlKey = ($locale === packageDefaultLocale($page)) ? '' : $locale;
165+
$name = $names[$locale] ?? $locale;
166+
167+
return [$urlKey => $name];
168+
})
169+
->all();
170+
}

0 commit comments

Comments
 (0)