summaryrefslogtreecommitdiff
path: root/src/application/i18n.php
blob: a1f2f2441c2d0bbccd087eab84ca247bdc8a8790 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php

use RR\Shunt\Context;
use RR\Shunt\Parser;
use RR\Shunt\Scanner;

const MESSAGE_DIR = __DIR__ . "/messages";

$__i18n_msg_store = [];
$__i18n_msg_store_plural = [];
$__i18n_msg_metadata = [];
/** @var string $__i18n_current_locale */
$__i18n_current_locale = "en";

const _I18N_MSGID = 0;
const _I18N_MSGSTR = 1;
const _I18N_MSGIDP = 2;
const _I18N_MSGSTRP = 3;
const _I18N_META = 10;

function i18n_parse(string $contents, ?string $filename = null): array {
    $syntax_error = fn(string $msg, int $line): never =>
        throw new Exception("i18n syntax error: $msg (in " . ($filename ?? "unknown") . ":" . $line . ")");
    $other_error = fn(string $msg, int $line): never =>
        throw new Exception("i18n error: $msg (in " . ($filename ?? "unknown") . ":" . $line . ")");

    $metadata = [];
    
    $msgs = [];
    $pmsgs = [];
    $lines = explode("\n", $contents);
    $currentId = "";
    $currentContext = "";
    $currentMessage = "";
    $currentIdP = [];
    $currentMessageP = [];
    $currentMetadataBuffer = [];
    $state = _I18N_MSGID;
    
    $processedLines = 0;
    foreach ($lines as $i => $ln) {
        $lnNum = $i + 1;
        if (trim($ln) === "")
            continue;

        if ($ln === "metadata({") {
            if ($processedLines > 0)
                $syntax_error("metadata must come first in file", $lnNum);
            $currentMetadataBuffer []= "{";
            $state = _I18N_META;
            ++$processedLines;
            continue;
        }
        if ($state == _I18N_META) {
            if ($ln === "})") {
                $currentMetadataBuffer []= "}";
                $state = _I18N_MSGSTR;
                $currentMetadataBuffer = implode("\n", $currentMetadataBuffer);
                $metadata = json_decode($currentMetadataBuffer, true);
            } else {
                $currentMetadataBuffer []= $ln;
            }
            ++$processedLines;
            continue;
        }

        switch ($ln[0]) {
            case "#":
                continue 2;
            case ":":
                if ($state === _I18N_MSGSTRP) {
                    // plural
                    if (count($currentIdP) > 0) {
                        if (isset($msgs[$currentId]))
                            $other_error("duplicate message id '$currentId'", $lnNum);
                        $pmsgs[$currentIdP[0]] = $currentMessageP;
                    }
                } else {
                    // singular
                    if ($currentId !== "") {
                        if ($currentContext !== "")
                            $currentId = $currentContext . "\x7F" . $currentId;
                        if (isset($msgs[$currentId]))
                            $other_error("duplicate message id '$currentId'", $lnNum);
                        $msgs[$currentId] = $currentMessage;
                    }
                }
                $currentIdP = [];
                $currentMessageP = [];
                $currentId = "";
                $currentContext = "";
                $currentMessage = "";
                if ($ln === ":...") {
                    // plural
                    $state = _I18N_MSGIDP;
                } else {
                    // singular
                    $currentId = json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                    $state = _I18N_MSGID;
                }
                break;
            case "-":
                if ($state === _I18N_MSGIDP) {
                    $_id = json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                    if ($currentContext !== "")
                        $_id = $currentContext . "\x7F" . $_id;
                    $currentIdP []= $_id;
                } elseif ($state === _I18N_MSGSTRP) {
                    $currentMessageP []= json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                } else
                    $syntax_error("cannot define multiple ids/messages in singular mode", $lnNum);
                break;
            case "=":
                if ($ln === "=...") {
                    // plural
                    if ($state !== _I18N_MSGIDP)
                        $syntax_error("cannot start plural message in singular mode", $lnNum);
                    $state = _I18N_MSGSTRP;
                } else {
                    // singular
                    $state = _I18N_MSGSTR;
                    $currentMessage = json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                }
                break;
            case "?":
                if ($state !== _I18N_MSGID)
                    $syntax_error("context must be defined before start of message", $lnNum);
                $currentContext = json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                break;
            case " ":
                if ($state === _I18N_MSGSTR)
                    $currentMessage .= json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                else
                    $currentId .= json_decode(substr($ln, 2)) ?? $syntax_error("malformed string", $lnNum);
                break;
            default:
                $syntax_error("invalid start of line '" . $ln[0] . "' (0x" . str_pad(strtoupper(dechex(ord($ln[0]))), 2, "0", STR_PAD_LEFT) . ")", $lnNum);
                break;
        }
        
        ++$processedLines;
    }

    if ($state === _I18N_MSGSTRP) {
        // plural
        if (count($currentIdP) > 0) {
            if (isset($msgs[$currentId]))
                $other_error("duplicate message id '$currentId'", $lnNum);
            $pmsgs[$currentIdP[0]] = $currentMessageP;
        }
    } else {
        // singular
        if ($currentId !== "") {
            if ($currentContext !== "")
                $currentId = $currentContext . "\x7F" . $currentId;
            if (isset($msgs[$currentId]))
                $other_error("duplicate message id '$currentId'", $lnNum);
            $msgs[$currentId] = $currentMessage;
        }
    }
    return [$metadata, $msgs, $pmsgs];
}

function i18n_locale(string $locale) {
    global $__i18n_current_locale;
    $__i18n_current_locale = $locale;
}

function i18n_get(string $msgid, array $params = [], ?string $context = null): string {
    global $__i18n_current_locale, $__i18n_msg_store;

    $key = $msgid;
    if ($context !== null)
        $key = $context . "\x7F" . $msgid;

    $msg = ($__i18n_msg_store[$__i18n_current_locale] ?? [])[$msgid] ?? $key;

    uksort($params, fn(string $a, string $b): int => strlen($b) <=> strlen($a));
    return str_replace(
        array_map(fn(string $k): string => "%$k%", array_keys($params)),
        array_values($params),
        $msg
    );
}

function i18n_metadata(string $lang): array {
    global $__i18n_msg_metadata;

    return $__i18n_msg_metadata[$lang] ?? [];
}

function i18n_get_plural(string $msgid_singular, string $msgid_plural, int $count, array $params = [], ?string $context = null): string {
    global $__i18n_current_locale, $__i18n_msg_metadata, $__i18n_msg_store_plural;

    $key = $msgid_singular;
    if ($context !== null)
        $key = $context . "\x7F" . $key;

    $msgs = ($__i18n_msg_store_plural[$__i18n_current_locale] ?? [])[$msgid_singular] ?? null;
    $msg = "";
    if ($msgs === null) {
        $msg = $count === 1 ? $msgid_singular : $msgid_plural;
    } else {
        $expression = (($__i18n_msg_metadata[$__i18n_current_locale] ?? [])["plural"] ?? [])["indexMapping"] ?? "n == 1 ? 0 : 1";
        $ctx = new Context();
        $ctx->def("ifelse", function(bool $c, $a, $b) { return $c ? $a : $b; });
        $ctx->def("n", $count);
        $parser = new Parser(new Scanner($expression));
        $index = $parser->reduce($ctx);
        $index = max(0, min(count($msgs) - 1, $index));
        $msg = $msgs[$index];
    }

    uksort($params, fn(string $a, string $b): int => strlen($b) <=> strlen($a));
    return str_replace(
        array_map(fn(string $k): string => "%$k%", array_keys($params)),
        array_values($params),
        $msg
    );
}

function i18n_get_current_locale(): string {
    global $__i18n_current_locale;
    return $__i18n_current_locale;
}

function i18n_get_available_locales(): array {
    global $__i18n_msg_store;
    return [
        "en",
        ...array_keys($__i18n_msg_store),
    ];
}

function i18n_get_message_store(string $locale): array {
    global $__i18n_msg_store, $__i18n_msg_store_plural;
    return [
        $__i18n_msg_store[$locale] ?? (object)[],
        $__i18n_msg_store_plural[$locale] ?? (object)[],
    ];
}

function __(string $msgid, array $params = [], ?string $context = null): string {
    return i18n_get($msgid, $params, $context);
}

function ___(string $msgid_singular, string $msgid_plural, int $count, array $params = [], ?string $context = null): string {
    return i18n_get_plural($msgid_singular, $msgid_plural, $count, $params, $context);
}

foreach (scandir(MESSAGE_DIR) as $ent) {
    $path = MESSAGE_DIR . "/" . $ent;
    if ($ent[0] === "." || !is_file($path) || strcasecmp(pathinfo($ent, PATHINFO_EXTENSION), "msg") !== 0)
        continue;
    $lang = pathinfo($ent, PATHINFO_FILENAME);
    [$meta, $msgs, $pmsgs] = i18n_parse(file_get_contents($path), $ent);
    $__i18n_msg_store[$lang] = $msgs;
    $__i18n_msg_store_plural[$lang] = $pmsgs;
    $__i18n_msg_metadata[$lang] = $meta;
}