Translator.php 14 KB

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