You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

491 lines
14 KiB

3 years ago
  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. * {@inheritdoc}
  208. */
  209. public function getCatalogues(): array
  210. {
  211. return array_values($this->catalogues);
  212. }
  213. /**
  214. * Gets the loaders.
  215. *
  216. * @return array LoaderInterface[]
  217. */
  218. protected function getLoaders()
  219. {
  220. return $this->loaders;
  221. }
  222. protected function loadCatalogue(string $locale)
  223. {
  224. if (null === $this->cacheDir) {
  225. $this->initializeCatalogue($locale);
  226. } else {
  227. $this->initializeCacheCatalogue($locale);
  228. }
  229. }
  230. protected function initializeCatalogue(string $locale)
  231. {
  232. $this->assertValidLocale($locale);
  233. try {
  234. $this->doLoadCatalogue($locale);
  235. } catch (NotFoundResourceException $e) {
  236. if (!$this->computeFallbackLocales($locale)) {
  237. throw $e;
  238. }
  239. }
  240. $this->loadFallbackCatalogues($locale);
  241. }
  242. private function initializeCacheCatalogue(string $locale): void
  243. {
  244. if (isset($this->catalogues[$locale])) {
  245. /* Catalogue already initialized. */
  246. return;
  247. }
  248. $this->assertValidLocale($locale);
  249. $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
  250. function (ConfigCacheInterface $cache) use ($locale) {
  251. $this->dumpCatalogue($locale, $cache);
  252. }
  253. );
  254. if (isset($this->catalogues[$locale])) {
  255. /* Catalogue has been initialized as it was written out to cache. */
  256. return;
  257. }
  258. /* Read catalogue from cache. */
  259. $this->catalogues[$locale] = include $cache->getPath();
  260. }
  261. private function dumpCatalogue(string $locale, ConfigCacheInterface $cache): void
  262. {
  263. $this->initializeCatalogue($locale);
  264. $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
  265. $content = sprintf(<<<EOF
  266. <?php
  267. use Symfony\Component\Translation\MessageCatalogue;
  268. \$catalogue = new MessageCatalogue('%s', %s);
  269. %s
  270. return \$catalogue;
  271. EOF
  272. ,
  273. $locale,
  274. var_export($this->getAllMessages($this->catalogues[$locale]), true),
  275. $fallbackContent
  276. );
  277. $cache->write($content, $this->catalogues[$locale]->getResources());
  278. }
  279. private function getFallbackContent(MessageCatalogue $catalogue): string
  280. {
  281. $fallbackContent = '';
  282. $current = '';
  283. $replacementPattern = '/[^a-z0-9_]/i';
  284. $fallbackCatalogue = $catalogue->getFallbackCatalogue();
  285. while ($fallbackCatalogue) {
  286. $fallback = $fallbackCatalogue->getLocale();
  287. $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
  288. $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
  289. $fallbackContent .= sprintf(<<<'EOF'
  290. $catalogue%s = new MessageCatalogue('%s', %s);
  291. $catalogue%s->addFallbackCatalogue($catalogue%s);
  292. EOF
  293. ,
  294. $fallbackSuffix,
  295. $fallback,
  296. var_export($this->getAllMessages($fallbackCatalogue), true),
  297. $currentSuffix,
  298. $fallbackSuffix
  299. );
  300. $current = $fallbackCatalogue->getLocale();
  301. $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
  302. }
  303. return $fallbackContent;
  304. }
  305. private function getCatalogueCachePath(string $locale): string
  306. {
  307. return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->cacheVary), true)), 0, 7), '/', '_').'.php';
  308. }
  309. /**
  310. * @internal
  311. */
  312. protected function doLoadCatalogue(string $locale): void
  313. {
  314. $this->catalogues[$locale] = new MessageCatalogue($locale);
  315. if (isset($this->resources[$locale])) {
  316. foreach ($this->resources[$locale] as $resource) {
  317. if (!isset($this->loaders[$resource[0]])) {
  318. if (\is_string($resource[1])) {
  319. throw new RuntimeException(sprintf('No loader is registered for the "%s" format when loading the "%s" resource.', $resource[0], $resource[1]));
  320. }
  321. throw new RuntimeException(sprintf('No loader is registered for the "%s" format.', $resource[0]));
  322. }
  323. $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
  324. }
  325. }
  326. }
  327. private function loadFallbackCatalogues(string $locale): void
  328. {
  329. $current = $this->catalogues[$locale];
  330. foreach ($this->computeFallbackLocales($locale) as $fallback) {
  331. if (!isset($this->catalogues[$fallback])) {
  332. $this->initializeCatalogue($fallback);
  333. }
  334. $fallbackCatalogue = new MessageCatalogue($fallback, $this->getAllMessages($this->catalogues[$fallback]));
  335. foreach ($this->catalogues[$fallback]->getResources() as $resource) {
  336. $fallbackCatalogue->addResource($resource);
  337. }
  338. $current->addFallbackCatalogue($fallbackCatalogue);
  339. $current = $fallbackCatalogue;
  340. }
  341. }
  342. protected function computeFallbackLocales(string $locale)
  343. {
  344. if (null === $this->parentLocales) {
  345. $this->parentLocales = json_decode(file_get_contents(__DIR__.'/Resources/data/parents.json'), true);
  346. }
  347. $locales = [];
  348. foreach ($this->fallbackLocales as $fallback) {
  349. if ($fallback === $locale) {
  350. continue;
  351. }
  352. $locales[] = $fallback;
  353. }
  354. while ($locale) {
  355. $parent = $this->parentLocales[$locale] ?? null;
  356. if ($parent) {
  357. $locale = 'root' !== $parent ? $parent : null;
  358. } elseif (\function_exists('locale_parse')) {
  359. $localeSubTags = locale_parse($locale);
  360. $locale = null;
  361. if (1 < \count($localeSubTags)) {
  362. array_pop($localeSubTags);
  363. $locale = locale_compose($localeSubTags) ?: null;
  364. }
  365. } elseif ($i = strrpos($locale, '_') ?: strrpos($locale, '-')) {
  366. $locale = substr($locale, 0, $i);
  367. } else {
  368. $locale = null;
  369. }
  370. if (null !== $locale) {
  371. array_unshift($locales, $locale);
  372. }
  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 (null !== $locale && 1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $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. }