PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/translation/Translator.php

https://gitlab.com/Pasantias/pasantiasASLG
PHP | 481 lines | 262 code | 69 blank | 150 comment | 25 complexity | 53e0a3b48d175845c891e108c5063ee9 MD5 | raw file
  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\Config\ConfigCacheInterface;
  14. use Symfony\Component\Config\ConfigCacheFactoryInterface;
  15. use Symfony\Component\Config\ConfigCacheFactory;
  16. /**
  17. * Translator.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class Translator implements TranslatorInterface, TranslatorBagInterface
  22. {
  23. /**
  24. * @var MessageCatalogueInterface[]
  25. */
  26. protected $catalogues = array();
  27. /**
  28. * @var string
  29. */
  30. protected $locale;
  31. /**
  32. * @var array
  33. */
  34. private $fallbackLocales = array();
  35. /**
  36. * @var LoaderInterface[]
  37. */
  38. private $loaders = array();
  39. /**
  40. * @var array
  41. */
  42. private $resources = array();
  43. /**
  44. * @var MessageSelector
  45. */
  46. private $selector;
  47. /**
  48. * @var string
  49. */
  50. private $cacheDir;
  51. /**
  52. * @var bool
  53. */
  54. private $debug;
  55. /**
  56. * @var ConfigCacheFactoryInterface|null
  57. */
  58. private $configCacheFactory;
  59. /**
  60. * Constructor.
  61. *
  62. * @param string $locale The locale
  63. * @param MessageSelector|null $selector The message selector for pluralization
  64. * @param string|null $cacheDir The directory to use for the cache
  65. * @param bool $debug Use cache in debug mode ?
  66. *
  67. * @throws \InvalidArgumentException If a locale contains invalid characters
  68. */
  69. public function __construct($locale, MessageSelector $selector = null, $cacheDir = null, $debug = false)
  70. {
  71. $this->setLocale($locale);
  72. $this->selector = $selector ?: new MessageSelector();
  73. $this->cacheDir = $cacheDir;
  74. $this->debug = $debug;
  75. }
  76. /**
  77. * Sets the ConfigCache factory to use.
  78. *
  79. * @param ConfigCacheFactoryInterface $configCacheFactory
  80. */
  81. public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
  82. {
  83. $this->configCacheFactory = $configCacheFactory;
  84. }
  85. /**
  86. * Adds a Loader.
  87. *
  88. * @param string $format The name of the loader (@see addResource())
  89. * @param LoaderInterface $loader A LoaderInterface instance
  90. */
  91. public function addLoader($format, LoaderInterface $loader)
  92. {
  93. $this->loaders[$format] = $loader;
  94. }
  95. /**
  96. * Adds a Resource.
  97. *
  98. * @param string $format The name of the loader (@see addLoader())
  99. * @param mixed $resource The resource name
  100. * @param string $locale The locale
  101. * @param string $domain The domain
  102. *
  103. * @throws \InvalidArgumentException If the locale contains invalid characters
  104. */
  105. public function addResource($format, $resource, $locale, $domain = null)
  106. {
  107. if (null === $domain) {
  108. $domain = 'messages';
  109. }
  110. $this->assertValidLocale($locale);
  111. $this->resources[$locale][] = array($format, $resource, $domain);
  112. if (in_array($locale, $this->fallbackLocales)) {
  113. $this->catalogues = array();
  114. } else {
  115. unset($this->catalogues[$locale]);
  116. }
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function setLocale($locale)
  122. {
  123. $this->assertValidLocale($locale);
  124. $this->locale = $locale;
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. public function getLocale()
  130. {
  131. return $this->locale;
  132. }
  133. /**
  134. * Sets the fallback locale(s).
  135. *
  136. * @param string|array $locales The fallback locale(s)
  137. *
  138. * @throws \InvalidArgumentException If a locale contains invalid characters
  139. *
  140. * @deprecated since version 2.3, to be removed in 3.0. Use setFallbackLocales() instead.
  141. */
  142. public function setFallbackLocale($locales)
  143. {
  144. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the setFallbackLocales() method instead.', E_USER_DEPRECATED);
  145. $this->setFallbackLocales(is_array($locales) ? $locales : array($locales));
  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 = array();
  158. foreach ($locales as $locale) {
  159. $this->assertValidLocale($locale);
  160. }
  161. $this->fallbackLocales = $locales;
  162. }
  163. /**
  164. * Gets the fallback locales.
  165. *
  166. * @return array $locales The fallback locales
  167. */
  168. public function getFallbackLocales()
  169. {
  170. return $this->fallbackLocales;
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function trans($id, array $parameters = array(), $domain = null, $locale = null)
  176. {
  177. if (null === $domain) {
  178. $domain = 'messages';
  179. }
  180. return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
  186. {
  187. if (null === $domain) {
  188. $domain = 'messages';
  189. }
  190. $id = (string) $id;
  191. $catalogue = $this->getCatalogue($locale);
  192. $locale = $catalogue->getLocale();
  193. while (!$catalogue->defines($id, $domain)) {
  194. if ($cat = $catalogue->getFallbackCatalogue()) {
  195. $catalogue = $cat;
  196. $locale = $catalogue->getLocale();
  197. } else {
  198. break;
  199. }
  200. }
  201. return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function getCatalogue($locale = null)
  207. {
  208. if (null === $locale) {
  209. $locale = $this->getLocale();
  210. } else {
  211. $this->assertValidLocale($locale);
  212. }
  213. if (!isset($this->catalogues[$locale])) {
  214. $this->loadCatalogue($locale);
  215. }
  216. return $this->catalogues[$locale];
  217. }
  218. /**
  219. * Gets the loaders.
  220. *
  221. * @return array LoaderInterface[]
  222. */
  223. protected function getLoaders()
  224. {
  225. return $this->loaders;
  226. }
  227. /**
  228. * Collects all messages for the given locale.
  229. *
  230. * @param string|null $locale Locale of translations, by default is current locale
  231. *
  232. * @return array[array] indexed by catalog
  233. */
  234. public function getMessages($locale = null)
  235. {
  236. $catalogue = $this->getCatalogue($locale);
  237. $messages = $catalogue->all();
  238. while ($catalogue = $catalogue->getFallbackCatalogue()) {
  239. $messages = array_replace_recursive($catalogue->all(), $messages);
  240. }
  241. return $messages;
  242. }
  243. /**
  244. * @param string $locale
  245. */
  246. protected function loadCatalogue($locale)
  247. {
  248. if (null === $this->cacheDir) {
  249. $this->initializeCatalogue($locale);
  250. } else {
  251. $this->initializeCacheCatalogue($locale);
  252. }
  253. }
  254. /**
  255. * @param string $locale
  256. */
  257. protected function initializeCatalogue($locale)
  258. {
  259. $this->assertValidLocale($locale);
  260. try {
  261. $this->doLoadCatalogue($locale);
  262. } catch (NotFoundResourceException $e) {
  263. if (!$this->computeFallbackLocales($locale)) {
  264. throw $e;
  265. }
  266. }
  267. $this->loadFallbackCatalogues($locale);
  268. }
  269. /**
  270. * @param string $locale
  271. */
  272. private function initializeCacheCatalogue($locale)
  273. {
  274. if (isset($this->catalogues[$locale])) {
  275. /* Catalogue already initialized. */
  276. return;
  277. }
  278. $this->assertValidLocale($locale);
  279. $self = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
  280. $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
  281. function (ConfigCacheInterface $cache) use ($self, $locale) {
  282. $self->dumpCatalogue($locale, $cache);
  283. }
  284. );
  285. if (isset($this->catalogues[$locale])) {
  286. /* Catalogue has been initialized as it was written out to cache. */
  287. return;
  288. }
  289. /* Read catalogue from cache. */
  290. $this->catalogues[$locale] = include $cache->getPath();
  291. }
  292. /**
  293. * This method is public because it needs to be callable from a closure in PHP 5.3. It should be made protected (or even private, if possible) in 3.0.
  294. *
  295. * @internal
  296. */
  297. public function dumpCatalogue($locale, ConfigCacheInterface $cache)
  298. {
  299. $this->initializeCatalogue($locale);
  300. $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
  301. $content = sprintf(<<<EOF
  302. <?php
  303. use Symfony\Component\Translation\MessageCatalogue;
  304. \$catalogue = new MessageCatalogue('%s', %s);
  305. %s
  306. return \$catalogue;
  307. EOF
  308. ,
  309. $locale,
  310. var_export($this->catalogues[$locale]->all(), true),
  311. $fallbackContent
  312. );
  313. $cache->write($content, $this->catalogues[$locale]->getResources());
  314. }
  315. private function getFallbackContent(MessageCatalogue $catalogue)
  316. {
  317. $fallbackContent = '';
  318. $current = '';
  319. $replacementPattern = '/[^a-z0-9_]/i';
  320. $fallbackCatalogue = $catalogue->getFallbackCatalogue();
  321. while ($fallbackCatalogue) {
  322. $fallback = $fallbackCatalogue->getLocale();
  323. $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
  324. $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
  325. $fallbackContent .= sprintf(<<<EOF
  326. \$catalogue%s = new MessageCatalogue('%s', %s);
  327. \$catalogue%s->addFallbackCatalogue(\$catalogue%s);
  328. EOF
  329. ,
  330. $fallbackSuffix,
  331. $fallback,
  332. var_export($fallbackCatalogue->all(), true),
  333. $currentSuffix,
  334. $fallbackSuffix
  335. );
  336. $current = $fallbackCatalogue->getLocale();
  337. $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
  338. }
  339. return $fallbackContent;
  340. }
  341. private function getCatalogueCachePath($locale)
  342. {
  343. return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
  344. }
  345. private function doLoadCatalogue($locale)
  346. {
  347. $this->catalogues[$locale] = new MessageCatalogue($locale);
  348. if (isset($this->resources[$locale])) {
  349. foreach ($this->resources[$locale] as $resource) {
  350. if (!isset($this->loaders[$resource[0]])) {
  351. throw new \RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
  352. }
  353. $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
  354. }
  355. }
  356. }
  357. private function loadFallbackCatalogues($locale)
  358. {
  359. $current = $this->catalogues[$locale];
  360. foreach ($this->computeFallbackLocales($locale) as $fallback) {
  361. if (!isset($this->catalogues[$fallback])) {
  362. $this->doLoadCatalogue($fallback);
  363. }
  364. $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
  365. foreach ($this->catalogues[$fallback]->getResources() as $resource) {
  366. $fallbackCatalogue->addResource($resource);
  367. }
  368. $current->addFallbackCatalogue($fallbackCatalogue);
  369. $current = $fallbackCatalogue;
  370. }
  371. }
  372. protected function computeFallbackLocales($locale)
  373. {
  374. $locales = array();
  375. foreach ($this->fallbackLocales as $fallback) {
  376. if ($fallback === $locale) {
  377. continue;
  378. }
  379. $locales[] = $fallback;
  380. }
  381. if (strrchr($locale, '_') !== false) {
  382. array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
  383. }
  384. return array_unique($locales);
  385. }
  386. /**
  387. * Asserts that the locale is valid, throws an Exception if not.
  388. *
  389. * @param string $locale Locale to tests
  390. *
  391. * @throws \InvalidArgumentException If the locale contains invalid characters
  392. */
  393. protected function assertValidLocale($locale)
  394. {
  395. if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
  396. throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
  397. }
  398. }
  399. /**
  400. * Provides the ConfigCache factory implementation, falling back to a
  401. * default implementation if necessary.
  402. *
  403. * @return ConfigCacheFactoryInterface $configCacheFactory
  404. */
  405. private function getConfigCacheFactory()
  406. {
  407. if (!$this->configCacheFactory) {
  408. $this->configCacheFactory = new ConfigCacheFactory($this->debug);
  409. }
  410. return $this->configCacheFactory;
  411. }
  412. }