-
Notifications
You must be signed in to change notification settings - Fork 0
/
Translator.hh
412 lines (342 loc) · 10.7 KB
/
Translator.hh
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Intl;
use Titon\Event\EmitsEvents;
use Titon\Event\Subject;
use Titon\Intl\Event\DetectedEvent;
use Titon\Intl\Event\DetectingEvent;
use Titon\Intl\Event\LocalizeEvent;
use Titon\Intl\Exception\MissingLocaleException;
use Titon\Io\DomainPathMap;
use Titon\Io\PathList;
use Titon\Utility\Config;
use Titon\Utility\State\Cookie;
use Titon\Utility\State\Server;
use \Locale as SystemLocale;
/**
* The `Translator` class handles all the necessary functionality for internationalization and
* localization. This includes defining which locales to support, loading translators,
* parsing resource bundles, and initializing environments.
*
* @link http://en.wikipedia.org/wiki/IETF_language_tag
* @link http://en.wikipedia.org/wiki/ISO_639
* @link http://en.wikipedia.org/wiki/ISO_3166-1
* @link http://loc.gov/standards/iso639-2/php/code_list.php
*
* @package Titon\Intl
*/
class Translator implements Subject {
use EmitsEvents;
/**
* Currently active locale based on the client.
*
* @var \Titon\Intl\Locale
*/
protected ?Locale $current;
/**
* Fallback locale if none can be found.
*
* @var \Titon\Intl\Locale
*/
protected ?Locale $fallback;
/**
* Message loader instance.
*
* @var \Titon\Intl\MessageLoader
*/
protected MessageLoader $loader;
/**
* Supported list of locales.
*
* @var \Titon\Intl\LocaleMap
*/
protected LocaleMap $locales = Map {};
/**
* Locale lookup paths.
*
* @var \Titon\Io\PathList
*/
protected PathList $localePaths = Set {};
/**
* Message lookup paths.
*
* @var \Titon\Io\DomainPathMap
*/
protected DomainPathMap $messagePaths = Map {};
/**
* Store the message loader.
*
* @param \Titon\Intl\MessageLoader $loader
*/
public function __construct(MessageLoader $loader) {
$this->loader = $loader;
$this->loader->setTranslator($this);
// Load internal resources
$this->addResourcePaths(MessageLoader::DEFAULT_DOMAIN, Set {__DIR__});
}
/**
* Map a locale to be supported during the locale detection and message translation process.
*
* @param \Titon\Intl\Locale $locale
* @return $this
*/
public function addLocale(Locale $locale): this {
$code = $locale->getCode();
if ($this->locales->contains($code)) {
return $this;
}
// Inherit resource paths
$locale->addLocalePaths($this->getLocalePaths());
foreach ($this->getMessagePaths() as $domain => $paths) {
$locale->addMessagePaths($domain, $paths);
}
// Set the locale
$this->locales[$code] = LocaleRegistry::set($locale);
// Set the parent as well
if ($parent = $locale->getParentLocale()) {
$this->addLocale($parent);
}
// Set fallback if none defined
if (!$this->fallback) {
$this->setFallback($code);
}
return $this;
}
/**
* Add multiple locale lookup paths.
*
* @param string $domain
* @param \Titon\Io\PathList $paths
* @return $this
*/
public function addLocalePaths(PathList $paths): this {
$this->localePaths->addAll($paths);
return $this;
}
/**
* Add multiple message lookup paths.
*
* @param string $domain
* @param \Titon\Io\PathList $paths
* @return $this
*/
public function addMessagePaths(string $domain, PathList $paths): this {
if (!$this->messagePaths->contains($domain)) {
$this->messagePaths[$domain] = Set {};
}
$this->messagePaths[$domain]->addAll($paths);
return $this;
}
/**
* Add multiple resource lookup paths that will automatically set locale and message paths.
*
* @param string $domain
* @param \Titon\Io\PathList $paths
* @return $this
*/
public function addResourcePaths(string $domain, PathList $paths): this {
$this->addLocalePaths($paths->map($path ==> sprintf('%s/locales', $path)));
$this->addMessagePaths($domain, $paths->map($path ==> sprintf('%s/messages', $path)));
return $this;
}
/**
* Gather a list of locale codes and fallback locale codes in descending order starting from the current locale.
*
* @return Set<string>
*/
public function cascade(): Set<string> {
$cycle = Set {};
foreach ([$this->current(), $this->getFallback()] as $locale) {
while ($locale instanceof Locale) {
$cycle[] = $locale->getCode();
$locale = $locale->getParentLocale();
}
}
return $cycle;
}
/**
* Return the currently detected locale.
*
* @return \Titon\Intl\Locale
*/
public function current(): ?Locale {
return $this->current;
}
/**
* Detect which locale to use based on the clients Accept-Language header.
*
* @return $this
* @throws \Titon\Intl\Exception\MissingTranslatorException
*/
public function detect(): this {
if (!$this->isEnabled()) {
return $this;
}
$current = null;
$cookieCode = (string) Cookie::get('locale');
$acceptLang = (string) Server::get('HTTP_ACCEPT_LANGUAGE');
$this->emit(new DetectingEvent($this));
// Determine via cookie
if ($cookieCode && $this->locales->contains($cookieCode)) {
$current = $cookieCode;
// Determine locale based on HTTP headers
} else if ($acceptLang) {
foreach (explode(',', mb_strtolower($acceptLang)) as $header) {
if (mb_strpos($header, ';') !== false) {
$header = mb_strstr($header, ';', true);
}
$header = Locale::canonicalize(trim($header));
if ($this->locales->contains($header)) {
$current = $header;
break;
}
}
}
// Set current to the fallback if none found
if ($current === null) {
$current = $this->getFallback()->getCode();
}
// Apply the locale
$newLocale = $this->localize((string) $current);
// Emit an event
invariant($newLocale !== null, 'Locale must be detected.');
$this->emit(new DetectedEvent($this, $newLocale));
return $this;
}
/**
* Return the fallback locale.
*
* @return \Titon\Intl\Locale
*/
public function getFallback(): Locale {
invariant($this->fallback !== null, 'A fallback Locale must be set.');
return $this->fallback;
}
/**
* Return a locale by code.
*
* @param string $code
* @return \Titon\Intl\Locale
* @throws \Titon\Intl\Exception\MissingLocaleException
*/
public function getLocale(string $code): Locale {
if ($this->locales->contains($code)) {
return $this->locales[$code];
}
throw new MissingLocaleException(sprintf('Locale %s does not exist', $code));
}
/**
* Return a list of supported locales.
*
* @return \Titon\Intl\LocaleMap
*/
public function getLocales(): LocaleMap {
return $this->locales;
}
/**
* Return all locale paths.
*
* @return \Titon\Io\PathList
*/
public function getLocalePaths(): PathList {
return $this->localePaths;
}
/**
* Return the message loader.
*
* @return \Titon\Intl\MessageLoader
*/
public function getMessageLoader(): MessageLoader {
return $this->loader;
}
/**
* Return all message paths.
*
* @return \Titon\Io\DomainPathMap
*/
public function getMessagePaths(): DomainPathMap {
return $this->messagePaths;
}
/**
* Does the current locale match the passed code?
*
* @param string $code
* @return bool
*/
public function is(string $code): bool {
$currentCode = $this->current()?->getCode();
return ($currentCode === $code || Locale::canonicalize($code) === $currentCode);
}
/**
* Globalization will be enabled if more than 1 locale has been setup.
*
* @return bool
*/
public function isEnabled(): bool {
return !$this->locales->isEmpty();
}
/**
* Set the system and application locale using the built in `setlocale()`.
*
* @link http://php.net/setlocale
* @link http://php.net/manual/locale.setdefault.php
*
* @uses Titon\Utility\Config
*
* @param string $code
* @return \Titon\Intl\Locale
*/
public function localize(string $code): Locale {
$newLocale = $this->getLocale(Locale::canonicalize($code));
// Emit change event
$event = new LocalizeEvent($this, $newLocale);
$this->emit($event);
// The locale may have changed from the event
$newLocale = $event->getLocale();
$code = $newLocale->getCode();
// Inherit from fallback if different than the new locale
$option = '';
// Find the correct locale from the system
foreach ([$newLocale, $this->getFallback()] as $locale) {
if (!$option && ($systemOption = shell_exec('locale -a | grep -i ' . $locale->getCode()))) {
$option = $systemOption;
}
}
// Set system locale
putenv('LC_ALL=' . $code);
setlocale(LC_ALL, $option ?: $code);
SystemLocale::setDefault(Locale::canonicalize($code, Locale::FORMAT_2));
$this->current = $newLocale;
Config::set('titon.locale.current', $code);
Config::set('titon.locale.cascade', $this->cascade());
return $newLocale;
}
/**
* Define the fallback locale to use if none can be found or is not supported.
*
* @uses Titon\Utility\Config
*
* @param string $code
* @return $this
* @throws \Titon\Intl\Exception\MissingLocaleException
*/
public function setFallback(string $code): this {
$this->fallback = $locale = $this->getLocale($code);
Config::set('titon.locale.fallback', $locale->getCode());
return $this;
}
/**
* Return a translated message from the message catalogs and optional interpolate parameters.
*
* @param string $key
* @param \Titon\Intl\ParamList $params
* @return string
*/
public function translate(string $key, ParamList $params = Vector {}): string {
return $this->getMessageLoader()->translate($key, $params);
}
}