Translator.php 14 KB

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