Translator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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\LogicException;
  16. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  17. use Symfony\Component\Translation\Exception\RuntimeException;
  18. use Symfony\Component\Translation\Formatter\ChoiceMessageFormatterInterface;
  19. use Symfony\Component\Translation\Formatter\IntlFormatterInterface;
  20. use Symfony\Component\Translation\Formatter\MessageFormatter;
  21. use Symfony\Component\Translation\Formatter\MessageFormatterInterface;
  22. use Symfony\Component\Translation\Loader\LoaderInterface;
  23. use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
  24. use Symfony\Contracts\Translation\TranslatorInterface;
  25. /**
  26. * @author Fabien Potencier <fabien@symfony.com>
  27. */
  28. class Translator implements LegacyTranslatorInterface, TranslatorInterface, TranslatorBagInterface
  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. if (null === $locale) {
  78. @trigger_error(sprintf('Passing "null" as the $locale argument to %s() is deprecated since Symfony 4.4.', __METHOD__), E_USER_DEPRECATED);
  79. }
  80. $this->setLocale($locale, false);
  81. if (null === $formatter) {
  82. $formatter = new MessageFormatter();
  83. }
  84. $this->formatter = $formatter;
  85. $this->cacheDir = $cacheDir;
  86. $this->debug = $debug;
  87. $this->cacheVary = $cacheVary;
  88. $this->hasIntlFormatter = $formatter instanceof IntlFormatterInterface;
  89. }
  90. public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  91. {
  92. $this->configCacheFactory = $configCacheFactory;
  93. }
  94. /**
  95. * Adds a Loader.
  96. *
  97. * @param string $format The name of the loader (@see addResource())
  98. */
  99. public function addLoader($format, LoaderInterface $loader)
  100. {
  101. $this->loaders[$format] = $loader;
  102. }
  103. /**
  104. * Adds a Resource.
  105. *
  106. * @param string $format The name of the loader (@see addLoader())
  107. * @param mixed $resource The resource name
  108. * @param string $locale The locale
  109. * @param string $domain The domain
  110. *
  111. * @throws InvalidArgumentException If the locale contains invalid characters
  112. */
  113. public function addResource($format, $resource, $locale, $domain = null)
  114. {
  115. if (null === $domain) {
  116. $domain = 'messages';
  117. }
  118. if (null === $locale) {
  119. @trigger_error(sprintf('Passing "null" to the third argument of the "%s" method has been deprecated since Symfony 4.4 and will throw an error in 5.0.', __METHOD__), E_USER_DEPRECATED);
  120. }
  121. $this->assertValidLocale($locale);
  122. $this->resources[$locale][] = [$format, $resource, $domain];
  123. if (\in_array($locale, $this->fallbackLocales)) {
  124. $this->catalogues = [];
  125. } else {
  126. unset($this->catalogues[$locale]);
  127. }
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function setLocale($locale)
  133. {
  134. if (null === $locale && (2 > \func_num_args() || func_get_arg(1))) {
  135. @trigger_error(sprintf('Passing "null" as the $locale argument to %s() is deprecated since Symfony 4.4.', __METHOD__), E_USER_DEPRECATED);
  136. }
  137. $this->assertValidLocale($locale);
  138. $this->locale = $locale;
  139. }
  140. /**
  141. * {@inheritdoc}
  142. */
  143. public function getLocale()
  144. {
  145. return $this->locale;
  146. }
  147. /**
  148. * Sets the fallback locales.
  149. *
  150. * @param array $locales The fallback locales
  151. *
  152. * @throws InvalidArgumentException If a locale contains invalid characters
  153. */
  154. public function setFallbackLocales(array $locales)
  155. {
  156. // needed as the fallback locales are linked to the already loaded catalogues
  157. $this->catalogues = [];
  158. foreach ($locales as $locale) {
  159. if (null === $locale) {
  160. @trigger_error(sprintf('Passing "null" as the $locale argument to %s() is deprecated since Symfony 4.4.', __METHOD__), E_USER_DEPRECATED);
  161. }
  162. $this->assertValidLocale($locale);
  163. }
  164. $this->fallbackLocales = $this->cacheVary['fallback_locales'] = $locales;
  165. }
  166. /**
  167. * Gets the fallback locales.
  168. *
  169. * @internal since Symfony 4.2
  170. *
  171. * @return array The fallback locales
  172. */
  173. public function getFallbackLocales()
  174. {
  175. return $this->fallbackLocales;
  176. }
  177. /**
  178. * {@inheritdoc}
  179. */
  180. public function trans($id, array $parameters = [], $domain = null, $locale = null)
  181. {
  182. if ('' === $id = (string) $id) {
  183. return '';
  184. }
  185. if (null === $domain) {
  186. $domain = 'messages';
  187. }
  188. $catalogue = $this->getCatalogue($locale);
  189. $locale = $catalogue->getLocale();
  190. while (!$catalogue->defines($id, $domain)) {
  191. if ($cat = $catalogue->getFallbackCatalogue()) {
  192. $catalogue = $cat;
  193. $locale = $catalogue->getLocale();
  194. } else {
  195. break;
  196. }
  197. }
  198. if ($this->hasIntlFormatter && $catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) {
  199. return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, $parameters);
  200. }
  201. return $this->formatter->format($catalogue->get($id, $domain), $locale, $parameters);
  202. }
  203. /**
  204. * {@inheritdoc}
  205. *
  206. * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter
  207. */
  208. public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
  209. {
  210. @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%%count%%" parameter.', __METHOD__), E_USER_DEPRECATED);
  211. if ('' === $id = (string) $id) {
  212. return '';
  213. }
  214. if (!$this->formatter instanceof ChoiceMessageFormatterInterface) {
  215. throw new LogicException(sprintf('The formatter "%s" does not support plural translations.', \get_class($this->formatter)));
  216. }
  217. if (null === $domain) {
  218. $domain = 'messages';
  219. }
  220. $catalogue = $this->getCatalogue($locale);
  221. $locale = $catalogue->getLocale();
  222. while (!$catalogue->defines($id, $domain)) {
  223. if ($cat = $catalogue->getFallbackCatalogue()) {
  224. $catalogue = $cat;
  225. $locale = $catalogue->getLocale();
  226. } else {
  227. break;
  228. }
  229. }
  230. if ($this->hasIntlFormatter && $catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) {
  231. return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, ['%count%' => $number] + $parameters);
  232. }
  233. return $this->formatter->choiceFormat($catalogue->get($id, $domain), $number, $locale, $parameters);
  234. }
  235. /**
  236. * {@inheritdoc}
  237. */
  238. public function getCatalogue($locale = null)
  239. {
  240. if (null === $locale) {
  241. $locale = $this->getLocale();
  242. } else {
  243. $this->assertValidLocale($locale);
  244. }
  245. if (!isset($this->catalogues[$locale])) {
  246. $this->loadCatalogue($locale);
  247. }
  248. return $this->catalogues[$locale];
  249. }
  250. /**
  251. * Gets the loaders.
  252. *
  253. * @return array LoaderInterface[]
  254. */
  255. protected function getLoaders()
  256. {
  257. return $this->loaders;
  258. }
  259. /**
  260. * @param string $locale
  261. */
  262. protected function loadCatalogue($locale)
  263. {
  264. if (null === $this->cacheDir) {
  265. $this->initializeCatalogue($locale);
  266. } else {
  267. $this->initializeCacheCatalogue($locale);
  268. }
  269. }
  270. /**
  271. * @param string $locale
  272. */
  273. protected function initializeCatalogue($locale)
  274. {
  275. $this->assertValidLocale($locale);
  276. try {
  277. $this->doLoadCatalogue($locale);
  278. } catch (NotFoundResourceException $e) {
  279. if (!$this->computeFallbackLocales($locale)) {
  280. throw $e;
  281. }
  282. }
  283. $this->loadFallbackCatalogues($locale);
  284. }
  285. private function initializeCacheCatalogue(string $locale): void
  286. {
  287. if (isset($this->catalogues[$locale])) {
  288. /* Catalogue already initialized. */
  289. return;
  290. }
  291. $this->assertValidLocale($locale);
  292. $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
  293. function (ConfigCacheInterface $cache) use ($locale) {
  294. $this->dumpCatalogue($locale, $cache);
  295. }
  296. );
  297. if (isset($this->catalogues[$locale])) {
  298. /* Catalogue has been initialized as it was written out to cache. */
  299. return;
  300. }
  301. /* Read catalogue from cache. */
  302. $this->catalogues[$locale] = include $cache->getPath();
  303. }
  304. private function dumpCatalogue(string $locale, ConfigCacheInterface $cache): void
  305. {
  306. $this->initializeCatalogue($locale);
  307. $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
  308. $content = sprintf(<<<EOF
  309. <?php
  310. use Symfony\Component\Translation\MessageCatalogue;
  311. \$catalogue = new MessageCatalogue('%s', %s);
  312. %s
  313. return \$catalogue;
  314. EOF
  315. ,
  316. $locale,
  317. var_export($this->getAllMessages($this->catalogues[$locale]), true),
  318. $fallbackContent
  319. );
  320. $cache->write($content, $this->catalogues[$locale]->getResources());
  321. }
  322. private function getFallbackContent(MessageCatalogue $catalogue): string
  323. {
  324. $fallbackContent = '';
  325. $current = '';
  326. $replacementPattern = '/[^a-z0-9_]/i';
  327. $fallbackCatalogue = $catalogue->getFallbackCatalogue();
  328. while ($fallbackCatalogue) {
  329. $fallback = $fallbackCatalogue->getLocale();
  330. $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
  331. $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
  332. $fallbackContent .= sprintf(<<<'EOF'
  333. $catalogue%s = new MessageCatalogue('%s', %s);
  334. $catalogue%s->addFallbackCatalogue($catalogue%s);
  335. EOF
  336. ,
  337. $fallbackSuffix,
  338. $fallback,
  339. var_export($this->getAllMessages($fallbackCatalogue), true),
  340. $currentSuffix,
  341. $fallbackSuffix
  342. );
  343. $current = $fallbackCatalogue->getLocale();
  344. $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
  345. }
  346. return $fallbackContent;
  347. }
  348. private function getCatalogueCachePath(string $locale): string
  349. {
  350. return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->cacheVary), true)), 0, 7), '/', '_').'.php';
  351. }
  352. /**
  353. * @internal
  354. */
  355. protected function doLoadCatalogue(string $locale): void
  356. {
  357. $this->catalogues[$locale] = new MessageCatalogue($locale);
  358. if (isset($this->resources[$locale])) {
  359. foreach ($this->resources[$locale] as $resource) {
  360. if (!isset($this->loaders[$resource[0]])) {
  361. throw new RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
  362. }
  363. $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
  364. }
  365. }
  366. }
  367. private function loadFallbackCatalogues(string $locale): void
  368. {
  369. $current = $this->catalogues[$locale];
  370. foreach ($this->computeFallbackLocales($locale) as $fallback) {
  371. if (!isset($this->catalogues[$fallback])) {
  372. $this->initializeCatalogue($fallback);
  373. }
  374. $fallbackCatalogue = new MessageCatalogue($fallback, $this->getAllMessages($this->catalogues[$fallback]));
  375. foreach ($this->catalogues[$fallback]->getResources() as $resource) {
  376. $fallbackCatalogue->addResource($resource);
  377. }
  378. $current->addFallbackCatalogue($fallbackCatalogue);
  379. $current = $fallbackCatalogue;
  380. }
  381. }
  382. protected function computeFallbackLocales($locale)
  383. {
  384. if (null === $this->parentLocales) {
  385. $parentLocales = json_decode(file_get_contents(__DIR__.'/Resources/data/parents.json'), true);
  386. }
  387. $locales = [];
  388. foreach ($this->fallbackLocales as $fallback) {
  389. if ($fallback === $locale) {
  390. continue;
  391. }
  392. $locales[] = $fallback;
  393. }
  394. while ($locale) {
  395. $parent = $parentLocales[$locale] ?? null;
  396. if (!$parent && false !== strrchr($locale, '_')) {
  397. $locale = substr($locale, 0, -\strlen(strrchr($locale, '_')));
  398. } elseif ('root' !== $parent) {
  399. $locale = $parent;
  400. } else {
  401. $locale = null;
  402. }
  403. if (null !== $locale) {
  404. array_unshift($locales, $locale);
  405. }
  406. }
  407. return array_unique($locales);
  408. }
  409. /**
  410. * Asserts that the locale is valid, throws an Exception if not.
  411. *
  412. * @param string $locale Locale to tests
  413. *
  414. * @throws InvalidArgumentException If the locale contains invalid characters
  415. */
  416. protected function assertValidLocale($locale)
  417. {
  418. if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
  419. throw new InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
  420. }
  421. }
  422. /**
  423. * Provides the ConfigCache factory implementation, falling back to a
  424. * default implementation if necessary.
  425. */
  426. private function getConfigCacheFactory(): ConfigCacheFactoryInterface
  427. {
  428. if (!$this->configCacheFactory) {
  429. $this->configCacheFactory = new ConfigCacheFactory($this->debug);
  430. }
  431. return $this->configCacheFactory;
  432. }
  433. private function getAllMessages(MessageCatalogueInterface $catalogue): array
  434. {
  435. $allMessages = [];
  436. foreach ($catalogue->all() as $domain => $messages) {
  437. if ($intlMessages = $catalogue->all($domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) {
  438. $allMessages[$domain.MessageCatalogue::INTL_DOMAIN_SUFFIX] = $intlMessages;
  439. $messages = array_diff_key($messages, $intlMessages);
  440. }
  441. if ($messages) {
  442. $allMessages[$domain] = $messages;
  443. }
  444. }
  445. return $allMessages;
  446. }
  447. }