rinkplanner/hub/app/i18n.php

72 lines
2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/**
* Texte der Hub-Oberfläche (Deutsch und Englisch).
*
* Die Sprache kommt aus dem Cookie RHUB_LANG und wird ausschließlich über den
* DE/EN-Umschalter gesetzt (Route /language). Standard ist Deutsch; der Hub
* ist eine geschlossene Beta und schaltet nicht automatisch um.
*
* t() liefert Text mit eingesetzten Platzhaltern ({name}); die Ausgabe wird
* an der Aufrufstelle mit e() maskiert. In den Texten steht kein HTML.
*/
const HUB_LOCALES = ['de', 'en'];
const HUB_DEFAULT_LOCALE = 'de';
const HUB_LOCALE_COOKIE = 'RHUB_LANG';
function hub_locale(): string
{
static $locale = null;
if ($locale !== null) {
return $locale;
}
$raw = strtolower(substr((string) ($_COOKIE[HUB_LOCALE_COOKIE] ?? ''), 0, 2));
$locale = in_array($raw, HUB_LOCALES, true) ? $raw : HUB_DEFAULT_LOCALE;
return $locale;
}
function hub_locale_set(string $locale): void
{
$locale = strtolower(substr($locale, 0, 2));
if (!in_array($locale, HUB_LOCALES, true)) {
return;
}
if (!headers_sent()) {
setcookie(HUB_LOCALE_COOKIE, $locale, [
'expires' => time() + 365 * 86400,
'path' => '/',
'secure' => is_https(),
'httponly' => false,
'samesite' => 'Lax',
]);
}
$_COOKIE[HUB_LOCALE_COOKIE] = $locale;
}
function hub_strings(): array
{
static $strings = null;
if ($strings === null) {
$strings = require HUB_APP . '/i18n_strings.php';
}
return $strings;
}
/** Text in der aktuellen Sprache; unbekannte Schlüssel geben den Schlüssel zurück. */
function t(string $key, array $args = []): string
{
$strings = hub_strings();
$locale = hub_locale();
$text = $strings[$locale][$key] ?? $strings[HUB_DEFAULT_LOCALE][$key] ?? $key;
if ($args !== []) {
$replace = [];
foreach ($args as $name => $value) {
$replace['{' . $name . '}'] = (string) $value;
}
$text = strtr($text, $replace);
}
return $text;
}