diff --git a/app/Config/Services.php b/app/Config/Services.php index 8ababb302..a85dffde2 100644 --- a/app/Config/Services.php +++ b/app/Config/Services.php @@ -3,6 +3,8 @@ namespace Config; use CodeIgniter\Config\BaseService; +use CodeIgniter\HTTP\IncomingRequest; +use Config\Services as AppServices; use HTMLPurifier; use HTMLPurifier_Config; @@ -32,6 +34,29 @@ class Services extends BaseService * } */ + /** + * Responsible for loading the language string translations. + * + * @return MY_Language + */ + public static function language(?string $locale = null, bool $getShared = true) + { + if ($getShared) { + return static::getSharedInstance('language', $locale)->setLocale($locale); + } + + if (AppServices::get('request') instanceof IncomingRequest) { + $requestLocale = AppServices::get('request')->getLocale(); + } else { + $requestLocale = Locale::getDefault(); + } + + // Use '?:' for empty string check + $locale = $locale ?: $requestLocale; + + return new \App\Libraries\MY_Language($locale); + } + private static $htmlPurifier; public static function htmlPurifier($getShared = true) diff --git a/app/Libraries/MY_Language.php b/app/Libraries/MY_Language.php new file mode 100644 index 000000000..7124261c3 --- /dev/null +++ b/app/Libraries/MY_Language.php @@ -0,0 +1,44 @@ +formatMessage($line, $args); + } + +// Parse out the file name and the actual alias. +// Will load the language file and strings. + [$file, $parsedLine] = $this->parseLine($line, $this->locale); + + $output = $this->getTranslationOutput($this->locale, $file, $parsedLine); + + if ($output === NULL && strpos($this->locale, '-')) + { + [$locale] = explode('-', $this->locale, 2); + + [$file, $parsedLine] = $this->parseLine($line, $locale); + + $output = $this->getTranslationOutput($locale, $file, $parsedLine); + } + + // if still not found, try English + if ($output === NULL || $output === "") + { + [$file, $parsedLine] = $this->parseLine($line, 'en'); + + $output = $this->getTranslationOutput('en', $file, $parsedLine); + } + + $output ??= $line; + + return $this->formatMessage($output, $args); + } + +}