diff options
Diffstat (limited to 'Digitigrade')
| -rw-r--r-- | Digitigrade/Text.php | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/Digitigrade/Text.php b/Digitigrade/Text.php new file mode 100644 index 0000000..952818b --- /dev/null +++ b/Digitigrade/Text.php @@ -0,0 +1,49 @@ +<?php +namespace Digitigrade; + +class Text { + private static string $defaultLanguage; + private static array $dictionary = []; + private string $translationKey; + + public function __construct(string $translationKey) { + $this->translationKey = $translationKey; + } + + public function __tostring(): string { + return $this->getInLanguage(self::$defaultLanguage); + } + + public function getInLanguage(string $language): string { + $dict = self::getDict($language); + if ($dict == null) { + Logger::getInstance()->warning("tried to use language '$language', which does not exist"); + return $this->translationKey; + } + if (isset($dict[$this->translationKey])) { + return $dict[$this->translationKey]; + } + if (isset($dict['FALLBACK'])) { + return $this->getInLanguage($dict['FALLBACK']); + } + Logger::getInstance()->warning("looking up translation key '$this->translationKey' in language '$language' failed"); + return $this->translationKey; + } + + private static function getDict(string $language): ?array { + if (isset(self::$dictionary[$language])) { + return self::$dictionary[$language]; + } + $filename = __DIR__ . "/../locale/$language.json"; + if (!is_file($filename)) { + return null; + } + $dict = json_decode(file_get_contents($filename), associative: true); + self::$dictionary[$language] = $dict; + return $dict; + } + + public static function setDefaultLanguage(string $language) { + self::$defaultLanguage = $language; + } +}
\ No newline at end of file |
