Aucune description

Translator.php 16KB

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