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