aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Text.php
blob: 952818ba0d0692999c358f5b70335d5e173eb0fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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;
    }
}