Translator.php 15 KB

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