forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguage.php
More file actions
319 lines (258 loc) · 8.97 KB
/
Language.php
File metadata and controls
319 lines (258 loc) · 8.97 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Language;
use IntlException;
use MessageFormatter;
/**
* Handle system messages and localization.
*
* Locale-based, built on top of PHP internationalization.
*
* @phpstan-type LoadedStrings array<string, array<string, array<string, string>|string>|string|list<string>>
*
* @see \CodeIgniter\Language\LanguageTest
*/
class Language
{
/**
* Stores the retrieved language lines
* from files for faster retrieval on
* second use.
*
* @var array<non-empty-string, array<non-empty-string, LoadedStrings>>
*/
protected $language = [];
/**
* The current locale to work with.
*
* @var non-empty-string
*/
protected $locale;
/**
* Boolean value whether the `intl` extension exists on the system.
*
* @var bool
*/
protected $intlSupport = false;
/**
* Stores filenames that have been
* loaded so that we don't load them again.
*
* @var array<non-empty-string, list<non-empty-string>>
*/
protected $loadedFiles = [];
/**
* @param non-empty-string $locale
*/
public function __construct(string $locale)
{
$this->locale = $locale;
if (class_exists(MessageFormatter::class)) {
$this->intlSupport = true;
}
}
/**
* Sets the current locale to use when performing string lookups.
*
* @param non-empty-string|null $locale
*
* @return $this
*/
public function setLocale(?string $locale = null)
{
if ($locale !== null) {
$this->locale = $locale;
}
return $this;
}
public function getLocale(): string
{
return $this->locale;
}
/**
* Parses the language string for a file, loads the file, if necessary,
* getting the line.
*
* @param array<array-key, float|int|string> $args
*
* @return list<string>|string
*/
public function getLine(string $line, array $args = [])
{
// 1. Format the line as-is if it does not have a file.
if (! str_contains($line, '.')) {
return $this->formatMessage($line, $args);
}
// 2. Get the formatted line using the file and line extracted from $line and the current locale.
[$file, $parsedLine] = $this->parseLine($line, $this->locale);
$output = $this->getTranslationOutput($this->locale, $file, $parsedLine);
// 3. If not found, try the locale without region (e.g., 'en-US' -> 'en').
if ($output === null && str_contains($this->locale, '-')) {
[$locale] = explode('-', $this->locale, 2);
[$file, $parsedLine] = $this->parseLine($line, $locale);
$output = $this->getTranslationOutput($locale, $file, $parsedLine);
}
// 4. If still not found, try English.
if ($output === null) {
[$file, $parsedLine] = $this->parseLine($line, 'en');
$output = $this->getTranslationOutput('en', $file, $parsedLine);
}
// 5. Fallback to the original line if no translation was found.
$output ??= $line;
return $this->formatMessage($output, $args);
}
/**
* @return list<string>|string|null
*/
protected function getTranslationOutput(string $locale, string $file, string $parsedLine)
{
$output = $this->language[$locale][$file][$parsedLine] ?? null;
if ($output !== null) {
return $output;
}
// Fallback: try to traverse dot notation
$current = $this->language[$locale][$file] ?? null;
if (is_array($current)) {
foreach (explode('.', $parsedLine) as $segment) {
$output = $current[$segment] ?? null;
if ($output === null) {
break;
}
if (is_array($output)) {
$current = $output;
}
}
if ($output !== null && ! is_array($output)) {
return $output;
}
}
// Final fallback: try two-level access manually
[$first, $rest] = explode('.', $parsedLine, 2) + ['', ''];
return $this->language[$locale][$file][$first][$rest] ?? null;
}
/**
* Parses the language string which should include the
* filename as the first segment (separated by period).
*
* @return array{non-empty-string, non-empty-string}
*/
protected function parseLine(string $line, string $locale): array
{
[$file, $line] = explode('.', $line, 2);
if (! isset($this->language[$locale][$file]) || ! array_key_exists($line, $this->language[$locale][$file])) {
$this->load($file, $locale);
}
return [$file, $line];
}
/**
* Advanced message formatting.
*
* @param list<string>|string $message
* @param array<array-key, float|int|string> $args
*
* @return ($message is list<string> ? list<string> : string)
*/
protected function formatMessage($message, array $args = [])
{
if (! $this->intlSupport || $args === []) {
return $message;
}
if (is_array($message)) {
foreach ($message as $index => $value) {
$message[$index] = $this->formatMessage($value, $args);
}
return $message;
}
$formatted = MessageFormatter::formatMessage($this->locale, $message, $args);
if ($formatted === false) {
// Format again to get the error message.
try {
$formatter = new MessageFormatter($this->locale, $message);
$formatted = $formatter->format($args);
$fmtError = sprintf('"%s" (%d)', $formatter->getErrorMessage(), $formatter->getErrorCode());
} catch (IntlException $e) {
$fmtError = sprintf('"%s" (%d)', $e->getMessage(), $e->getCode());
}
$argsAsString = sprintf('"%s"', implode('", "', $args));
$urlEncodedArgs = sprintf('"%s"', implode('", "', array_map(rawurlencode(...), $args)));
log_message('error', sprintf(
'Invalid message format: $message: "%s", $args: %s (urlencoded: %s), MessageFormatter Error: %s',
$message,
$argsAsString,
$urlEncodedArgs,
$fmtError,
));
return $message . "\n【Warning】Also, invalid string(s) was passed to the Language class. See log file for details.";
}
return $formatted;
}
/**
* Loads a language file in the current locale. If $return is true,
* will return the file's contents, otherwise will merge with
* the existing language lines.
*
* @return ($return is true ? LoadedStrings : null)
*/
protected function load(string $file, string $locale, bool $return = false)
{
if (! array_key_exists($locale, $this->loadedFiles)) {
$this->loadedFiles[$locale] = [];
}
if (in_array($file, $this->loadedFiles[$locale], true)) {
// Don't load it more than once.
return [];
}
if (! array_key_exists($locale, $this->language)) {
$this->language[$locale] = [];
}
if (! array_key_exists($file, $this->language[$locale])) {
$this->language[$locale][$file] = [];
}
$path = "Language/{$locale}/{$file}.php";
$lang = $this->requireFile($path);
if ($return) {
return $lang;
}
$this->loadedFiles[$locale][] = $file;
// Merge our string
$this->language[$locale][$file] = $lang;
return null;
}
/**
* A simple method for including files that can be overridden during testing.
*
* @return LoadedStrings
*/
protected function requireFile(string $path): array
{
$files = service('locator')->search($path, 'php', false);
$strings = [];
foreach ($files as $file) {
if (is_file($file)) {
// On some OS, we were seeing failures on this command returning boolean instead
// of array during testing, so we've removed the require_once for now.
$loadedStrings = require $file;
if (is_array($loadedStrings)) {
/** @var LoadedStrings $loadedStrings */
$strings[] = $loadedStrings;
}
}
}
$count = count($strings);
if ($count > 1) {
$base = array_shift($strings);
$strings = array_replace_recursive($base, ...$strings);
} elseif ($count === 1) {
$strings = $strings[0];
}
return $strings;
}
}