Skip to content

Commit

Permalink
chore: Refactor localize()
Browse files Browse the repository at this point in the history
  • Loading branch information
darcywong00 committed Dec 12, 2024
1 parent e4fb670 commit 6bd2621
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 23 deletions.
42 changes: 37 additions & 5 deletions _includes/locale/Locale.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
class Locale {
public const DEFAULT_LOCALE = 'en';

public const CROWDIN_LOCALES = array(
'en',
'es-ES',
'fr-FR'
);

// xx-YY locale as specified in crowdin %locale%
private static $currentLocale = Locale::DEFAULT_LOCALE;

Expand Down Expand Up @@ -34,11 +40,7 @@ public static function overrideCurrentLocale($locale) {
* @return true if valid locale
*/
public static function validateLocale($locale) {
if(preg_match('/^[[:alpha:]]{2,3}(-[[:alpha:]]{2,3})?$/i', $locale)) {
return true;
}

return false;
return in_array($locale, Locale::CROWDIN_LOCALES);
}

/**
Expand Down Expand Up @@ -66,6 +68,36 @@ public static function setTextDomain($basename) {
}
}

/**
* Returns an array of localized strings from the specified $domain-locale.po file
* for the current locale.
* @param $domain - base filename of the .po files (not including -xx-YY locale)
* @param $strings - Array of msgid's in the .po files
* @return Array of localized strings for the current locale
*/
public static function localize($domain, $strings) {
foreach(Locale::CROWDIN_LOCALES as $l) {
if ($l == Locale::DEFAULT_LOCALE) {
// Skip English
continue;
}

bindtextdomain("$domain-$l", __DIR__);
}

$previousTextDomain = textdomain(NULL);
Locale::setTextDomain($domain);

$result = [];
foreach($strings as $s) {
$result[$s] = _($s);
}

// Restore textdomain
textdomain($previousTextDomain);
return $result;
}

/**
* Wrapper to format string with gettext '_(' alias and variable args
* @param $s - the format string
Expand Down
19 changes: 1 addition & 18 deletions keyboards/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

// Of array of strings at top of file
// by msgid
$keyboardIndexStrings = localize('keyboards', [
$keyboardIndexStrings = Locale::localize('keyboards', [
'Keyboard Search',
'Keyman Keyboard Search',
'Keyboard search%s',
Expand All @@ -34,23 +34,6 @@
'searches for Tigrigna %sEthiopia%s',
]);

function localize($domain, $strings) {
bindtextdomain("$domain-fr-FR", __DIR__ . "/../_includes/locale");
bindtextdomain("$domain-es-ES", __DIR__ . "/../_includes/locale");

$previousTextDomain = textdomain(NULL);
Locale::setTextDomain($domain);

$result = [];
foreach($strings as $s) {
$result[$s] = _($s);
}

// Restore textdomain
textdomain($previousTextDomain);
return $result;
}

$head_options = [
'title' => $keyboardIndexStrings['Keyboard Search'],
'description' => $keyboardIndexStrings['Keyman Keyboard Search'],
Expand Down

0 comments on commit 6bd2621

Please sign in to comment.