Translator.php 12KB

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