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