Debian Codegraph @

lib/3rdParty/composer/symfony/translation/Translator.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Translation;
13
14 use Symfony\Component\Config\ConfigCacheFactory;
15 use Symfony\Component\Config\ConfigCacheFactoryInterface;
16 use Symfony\Component\Config\ConfigCacheInterface;
17 use Symfony\Component\Translation\Exception\InvalidArgumentException;
18 use Symfony\Component\Translation\Exception\NotFoundResourceException;
19 use Symfony\Component\Translation\Exception\RuntimeException;
20 use Symfony\Component\Translation\Formatter\IntlFormatterInterface;
21 use Symfony\Component\Translation\Formatter\MessageFormatter;
22 use Symfony\Component\Translation\Formatter\MessageFormatterInterface;
23 use Symfony\Component\Translation\Loader\LoaderInterface;
24 use Symfony\Contracts\Translation\LocaleAwareInterface;
25 use Symfony\Contracts\Translation\TranslatableInterface;
26 use Symfony\Contracts\Translation\TranslatorInterface;
27
28 // Help opcache.preload discover always-needed symbols
29 class_exists(MessageCatalogue::class);
30
31 /**
32 * @author Fabien Potencier <[email protected]>
33 */
34 class Translator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface
35 {
36 /**
37 * @var MessageCatalogueInterface[]
38 */
39 protected array $catalogues = [];
40
41 private string $locale;
42
43 /**
44 * @var string[]
45 */
46 private array $fallbackLocales = [];
47
48 /**
49 * @var LoaderInterface[]
50 */
51 private array $loaders = [];
52
53 private array $resources = [];
54
55 private MessageFormatterInterface $formatter;
56
57 private ?ConfigCacheFactoryInterface $configCacheFactory;
58
59 private array $parentLocales;
60
61 private bool $hasIntlFormatter;
62
63 /**
64 * @var array<string, string|int|float|TranslatableInterface>
65 */
66 private array $globalParameters = [];
67
68 /**
69 * @var array<string, string|int|float>
70 */
71 private array $globalTranslatedParameters = [];
72
73 /**
74 * @throws InvalidArgumentException If a locale contains invalid characters
75 */
76 public function __construct(
77 string $locale,
78 ?MessageFormatterInterface $formatter = null,
79 private ?string $cacheDir = null,
80 private bool $debug = false,
81 private array $cacheVary = [],
82 ) {
83 $this->setLocale($locale);
84
85 $this->formatter = $formatter ??= new MessageFormatter();
86 $this->hasIntlFormatter = $formatter instanceof IntlFormatterInterface;
87 }
88
89 public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory): void
90 {
91 $this->configCacheFactory = $configCacheFactory;
92 }
93
94 /**
95 * Adds a Loader.
96 *
97 * @param string $format The name of the loader (@see addResource())
98 */
99 public function addLoader(string $format, LoaderInterface $loader): void
100 {
101 $this->loaders[$format] = $loader;
102 }
103
104 /**
105 * Adds a Resource.
106 *
107 * @param string $format The name of the loader (@see addLoader())
108 * @param mixed $resource The resource name
109 *
110 * @throws InvalidArgumentException If the locale contains invalid characters
111 */
112 public function addResource(string $format, mixed $resource, string $locale, ?string $domain = null): void
113 {
114 $domain ??= 'messages';
115
116 $this->assertValidLocale($locale);
117 $locale ?: $locale = class_exists(\Locale::class) ? \Locale::getDefault() : 'en';
118
119 $this->resources[$locale][] = [$format, $resource, $domain];
120
121 if (\in_array($locale, $this->fallbackLocales, true)) {
122 $this->catalogues = [];
123 } else {
124 unset($this->catalogues[$locale]);
125 }
126 }
127
128 public function setLocale(string $locale): void
129 {
130 $this->assertValidLocale($locale);
131 $this->locale = $locale;
132 }
133
134 public function getLocale(): string
135 {
136 return $this->locale ?: (class_exists(\Locale::class) ? \Locale::getDefault() : 'en');
137 }
138
139 /**
140 * Sets the fallback locales.
141 *
142 * @param string[] $locales
143 *
144 * @throws InvalidArgumentException If a locale contains invalid characters
145 */
146 public function setFallbackLocales(array $locales): void
147 {
148 // needed as the fallback locales are linked to the already loaded catalogues
149 $this->catalogues = [];
150
151 foreach ($locales as $locale) {
152 $this->assertValidLocale($locale);
153 }
154
155 $this->fallbackLocales = $this->cacheVary['fallback_locales'] = $locales;
156 }
157
158 /**
159 * Gets the fallback locales.
160 *
161 * @internal
162 */
163 public function getFallbackLocales(): array
164 {
165 return $this->fallbackLocales;
166 }
167
168 public function addGlobalParameter(string $id, string|int|float|TranslatableInterface $value): void
169 {
170 $this->globalParameters[$id] = $value;
171 $this->globalTranslatedParameters = [];
172 }
173
174 public function getGlobalParameters(): array
175 {
176 return $this->globalParameters;
177 }
178
179 public function trans(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
180 {
181 if (null === $id || '' === $id) {
182 return '';
183 }
184
185 $domain ??= 'messages';
186
187 $catalogue = $this->getCatalogue($locale);
188 $locale = $catalogue->getLocale();
189 while (!$catalogue->defines($id, $domain)) {
190 if ($cat = $catalogue->getFallbackCatalogue()) {
191 $catalogue = $cat;
192 $locale = $catalogue->getLocale();
193 } else {
194 break;
195 }
196 }
197
198 foreach ($parameters as $key => $value) {
199 if ($value instanceof TranslatableInterface) {
200 $parameters[$key] = $value->trans($this, $locale);
201 }
202 }
203
204 if (null === $globalParameters = &$this->globalTranslatedParameters[$locale]) {
205 $globalParameters = $this->globalParameters;
206 foreach ($globalParameters as $key => $value) {
207 if ($value instanceof TranslatableInterface) {
208 $globalParameters[$key] = $value->trans($this, $locale);
209 }
210 }
211 }
212
213 if ($globalParameters) {
214 $parameters += $globalParameters;
215 }
216
217 $len = \strlen(MessageCatalogue::INTL_DOMAIN_SUFFIX);
218 if ($this->hasIntlFormatter
219 && ($catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)
220 || (\strlen($domain) > $len && 0 === substr_compare($domain, MessageCatalogue::INTL_DOMAIN_SUFFIX, -$len, $len)))
221 ) {
222 return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, $parameters);
223 }
224
225 return $this->formatter->format($catalogue->get($id, $domain), $locale, $parameters);
226 }
227
228 public function getCatalogue(?string $locale = null): MessageCatalogueInterface
229 {
230 if (!$locale) {
231 $locale = $this->getLocale();
232 } else {
233 $this->assertValidLocale($locale);
234 }
235
236 if (!isset($this->catalogues[$locale])) {
237 $this->loadCatalogue($locale);
238 }
239
240 return $this->catalogues[$locale];
241 }
242
243 public function getCatalogues(): array
244 {
245 return array_values($this->catalogues);
246 }
247
248 /**
249 * Gets the loaders.
250 *
251 * @return LoaderInterface[]
252 */
253 protected function getLoaders(): array
254 {
255 return $this->loaders;
256 }
257
258 protected function loadCatalogue(string $locale): void
259 {
260 if (null === $this->cacheDir) {
261 $this->initializeCatalogue($locale);
262 } else {
263 $this->initializeCacheCatalogue($locale);
264 }
265 }
266
267 protected function initializeCatalogue(string $locale): void
268 {
269 $this->assertValidLocale($locale);
270
271 try {
272 $this->doLoadCatalogue($locale);
273 } catch (NotFoundResourceException $e) {
274 if (!$this->computeFallbackLocales($locale)) {
275 throw $e;
276 }
277 }
278 $this->loadFallbackCatalogues($locale);
279 }
280
281 private function initializeCacheCatalogue(string $locale): void
282 {
283 if (isset($this->catalogues[$locale])) {
284 /* Catalogue already initialized. */
285 return;
286 }
287
288 $this->assertValidLocale($locale);
289 $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
290 function (ConfigCacheInterface $cache) use ($locale) {
291 $this->dumpCatalogue($locale, $cache);
292 }
293 );
294
295 if (isset($this->catalogues[$locale])) {
296 /* Catalogue has been initialized as it was written out to cache. */
297 return;
298 }
299
300 /* Read catalogue from cache. */
301 $this->catalogues[$locale] = include $cache->getPath();
302 }
303
304 private function dumpCatalogue(string $locale, ConfigCacheInterface $cache): void
305 {
306 $this->initializeCatalogue($locale);
307 $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
308
309 $content = \sprintf(<<<EOF
310 <?php
311
312 use Symfony\Component\Translation\MessageCatalogue;
313
314 \$catalogue = new MessageCatalogue('%s', %s);
315
316 %s
317 return \$catalogue;
318
319 EOF,
320 $locale,
321 var_export($this->getAllMessages($this->catalogues[$locale]), true),
322 $fallbackContent
323 );
324
325 $cache->write($content, $this->catalogues[$locale]->getResources());
326 }
327
328 private function getFallbackContent(MessageCatalogue $catalogue): string
329 {
330 $fallbackContent = '';
331 $current = '';
332 $replacementPattern = '/[^a-z0-9_]/i';
333 $fallbackCatalogue = $catalogue->getFallbackCatalogue();
334 while ($fallbackCatalogue) {
335 $fallback = $fallbackCatalogue->getLocale();
336 $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
337 $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
338
339 $fallbackContent .= \sprintf(<<<'EOF'
340 $catalogue%s = new MessageCatalogue('%s', %s);
341 $catalogue%s->addFallbackCatalogue($catalogue%s);
342
343 EOF,
344 $fallbackSuffix,
345 $fallback,
346 var_export($this->getAllMessages($fallbackCatalogue), true),
347 $currentSuffix,
348 $fallbackSuffix
349 );
350 $current = $fallbackCatalogue->getLocale();
351 $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
352 }
353
354 return $fallbackContent;
355 }
356
357 private function getCatalogueCachePath(string $locale): string
358 {
359 return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('xxh128', serialize($this->cacheVary), true)), 0, 7), '/', '_').'.php';
360 }
361
362 /**
363 * @internal
364 */
365 protected function doLoadCatalogue(string $locale): void
366 {
367 $this->catalogues[$locale] = new MessageCatalogue($locale);
368
369 if (isset($this->resources[$locale])) {
370 foreach ($this->resources[$locale] as $resource) {
371 if (!isset($this->loaders[$resource[0]])) {
372 if (\is_string($resource[1])) {
373 throw new RuntimeException(\sprintf('No loader is registered for the "%s" format when loading the "%s" resource.', $resource[0], $resource[1]));
374 }
375
376 throw new RuntimeException(\sprintf('No loader is registered for the "%s" format.', $resource[0]));
377 }
378 $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
379 }
380 }
381 }
382
383 private function loadFallbackCatalogues(string $locale): void
384 {
385 $current = $this->catalogues[$locale];
386
387 foreach ($this->computeFallbackLocales($locale) as $fallback) {
388 if (!isset($this->catalogues[$fallback])) {
389 $this->initializeCatalogue($fallback);
390 }
391
392 $fallbackCatalogue = new MessageCatalogue($fallback, $this->getAllMessages($this->catalogues[$fallback]));
393 foreach ($this->catalogues[$fallback]->getResources() as $resource) {
394 $fallbackCatalogue->addResource($resource);
395 }
396 $current->addFallbackCatalogue($fallbackCatalogue);
397 $current = $fallbackCatalogue;
398 }
399 }
400
401 protected function computeFallbackLocales(string $locale): array
402 {
403 $this->parentLocales ??= json_decode(file_get_contents(__DIR__.'/Resources/data/parents.json'), true);
404
405 $originLocale = $locale;
406 $locales = [];
407
408 while ($locale) {
409 $parent = $this->parentLocales[$locale] ?? null;
410
411 if ($parent) {
412 $locale = 'root' !== $parent ? $parent : null;
413 } elseif (\function_exists('locale_parse')) {
414 $localeSubTags = locale_parse($locale);
415 $locale = null;
416 if (1 < \count($localeSubTags)) {
417 array_pop($localeSubTags);
418 $locale = locale_compose($localeSubTags) ?: null;
419 }
420 } elseif ($i = strrpos($locale, '_') ?: strrpos($locale, '-')) {
421 $locale = substr($locale, 0, $i);
422 } else {
423 $locale = null;
424 }
425
426 if (null !== $locale) {
427 $locales[] = $locale;
428 }
429 }
430
431 foreach ($this->fallbackLocales as $fallback) {
432 if ($fallback === $originLocale) {
433 continue;
434 }
435
436 $locales[] = $fallback;
437 }
438
439 return array_unique($locales);
440 }
441
442 /**
443 * Asserts that the locale is valid, throws an Exception if not.
444 *
445 * @throws InvalidArgumentException If the locale contains invalid characters
446 */
447 protected function assertValidLocale(string $locale): void
448 {
449 if (!preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
450 throw new InvalidArgumentException(\sprintf('Invalid "%s" locale.', $locale));
451 }
452 }
453
454 /**
455 * Provides the ConfigCache factory implementation, falling back to a
456 * default implementation if necessary.
457 */
458 private function getConfigCacheFactory(): ConfigCacheFactoryInterface
459 {
460 $this->configCacheFactory ??= new ConfigCacheFactory($this->debug);
461
462 return $this->configCacheFactory;
463 }
464
465 private function getAllMessages(MessageCatalogueInterface $catalogue): array
466 {
467 $allMessages = [];
468
469 foreach ($catalogue->all() as $domain => $messages) {
470 if ($intlMessages = $catalogue->all($domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) {
471 $allMessages[$domain.MessageCatalogue::INTL_DOMAIN_SUFFIX] = $intlMessages;
472 $messages = array_diff_key($messages, $intlMessages);
473 }
474 if ($messages) {
475 $allMessages[$domain] = $messages;
476 }
477 }
478
479 return $allMessages;
480 }
481 }