Improve translations logic

This commit is contained in:
Jay Trees 2022-03-22 13:43:54 +01:00
parent c131afaf64
commit c811b9e315
3 changed files with 32 additions and 28 deletions

View file

@ -79,6 +79,32 @@ if (isset($api)) {
return;
}
/**
* Language
*/
/** Determine Locale */
$userLocale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
$locales = array_filter(
array_map(
function ($value) {
if ('po' === pathinfo($value, PATHINFO_EXTENSION)) {
return pathinfo($value, PATHINFO_FILENAME);
}
},
scandir(ROOT . '/translations')
)
);
$locale = \Locale::lookup($locales, $userLocale, false, 'en');
/** Load Translation */
$translationFilepath = ROOT . '/translations/' . $locale . '.po';
$translations = null;
if (file_exists($translationFilepath)) {
$loader = new \Gettext\Loader\PoLoader();
$translations = $loader->loadFile($translationFilepath);
}
/**
* Install
*/

View file

@ -157,20 +157,9 @@ class Page
}
/**
* Determine Locale
* Locale
*/
$userLocale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
$locales = array_filter(
array_map(
function ($value) {
if ('po' === pathinfo($value, PATHINFO_EXTENSION)) {
return pathinfo($value, PATHINFO_FILENAME);
}
},
scandir(ROOT . '/translations')
)
);
$locale = \Locale::lookup($locales, $userLocale, false, 'en');
global $locale;
$this->language = $locale;
}

View file

@ -6,25 +6,14 @@
* @author Jay Trees <github.jay@grandel.anonaddy.me>
*/
use Gettext\Loader\PoLoader;
function __(string $text)
{
global $page;
global $translations;
if (!isset($page->language)) {
return $text;
}
$translation = null;
/**
* Use file
*/
$translationFilepath = ROOT . '/translations/' . $page->language . '.po';
if (file_exists($translationFilepath)) {
$loader = new PoLoader();
$translations = $loader->loadFile($translationFilepath);
$translation = $translations->find(null, $text);
if ($translations) {
$translation = $translations->find(null, $text);
if ($translation) {
return $translation->getTranslation();