PageRenderTime 55ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/engine/System/vendor/symfony/translation/Translator.php

https://gitlab.com/leon0399/damnit-engine
PHP | 438 lines | 244 code | 65 blank | 129 comment | 24 complexity | bee60d7f2c94b48028da9e653ccb0560 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. private $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 locales.
  135. *
  136. * @param array $locales The fallback locales
  137. *
  138. * @throws \InvalidArgumentException If a locale contains invalid characters
  139. */
  140. public function setFallbackLocales(array $locales)
  141. {
  142. // needed as the fallback locales are linked to the already loaded catalogues
  143. $this->catalogues = array();
  144. foreach ($locales as $locale) {
  145. $this->assertValidLocale($locale);
  146. }
  147. $this->fallbackLocales = $locales;
  148. }
  149. /**
  150. * Gets the fallback locales.
  151. *
  152. * @return array $locales The fallback locales
  153. */
  154. public function getFallbackLocales()
  155. {
  156. return $this->fallbackLocales;
  157. }
  158. /**
  159. * {@inheritdoc}
  160. */
  161. public function trans($id, array $parameters = array(), $domain = null, $locale = null)
  162. {
  163. if (null === $domain) {
  164. $domain = 'messages';
  165. }
  166. return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
  172. {
  173. if (null === $domain) {
  174. $domain = 'messages';
  175. }
  176. $id = (string) $id;
  177. $catalogue = $this->getCatalogue($locale);
  178. $locale = $catalogue->getLocale();
  179. while (!$catalogue->defines($id, $domain)) {
  180. if ($cat = $catalogue->getFallbackCatalogue()) {
  181. $catalogue = $cat;
  182. $locale = $catalogue->getLocale();
  183. } else {
  184. break;
  185. }
  186. }
  187. return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
  188. }
  189. /**
  190. * {@inheritdoc}
  191. */
  192. public function getCatalogue($locale = null)
  193. {
  194. if (null === $locale) {
  195. $locale = $this->getLocale();
  196. } else {
  197. $this->assertValidLocale($locale);
  198. }
  199. if (!isset($this->catalogues[$locale])) {
  200. $this->loadCatalogue($locale);
  201. }
  202. return $this->catalogues[$locale];
  203. }
  204. /**
  205. * Gets the loaders.
  206. *
  207. * @return array LoaderInterface[]
  208. */
  209. protected function getLoaders()
  210. {
  211. return $this->loaders;
  212. }
  213. /**
  214. * @param string $locale
  215. */
  216. protected function loadCatalogue($locale)
  217. {
  218. if (null === $this->cacheDir) {
  219. $this->initializeCatalogue($locale);
  220. } else {
  221. $this->initializeCacheCatalogue($locale);
  222. }
  223. }
  224. /**
  225. * @param string $locale
  226. */
  227. protected function initializeCatalogue($locale)
  228. {
  229. $this->assertValidLocale($locale);
  230. try {
  231. $this->doLoadCatalogue($locale);
  232. } catch (NotFoundResourceException $e) {
  233. if (!$this->computeFallbackLocales($locale)) {
  234. throw $e;
  235. }
  236. }
  237. $this->loadFallbackCatalogues($locale);
  238. }
  239. /**
  240. * @param string $locale
  241. */
  242. private function initializeCacheCatalogue($locale)
  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($locale, ConfigCacheInterface $cache)
  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->catalogues[$locale]->all(), true),
  275. $fallbackContent
  276. );
  277. $cache->write($content, $this->catalogues[$locale]->getResources());
  278. }
  279. private function getFallbackContent(MessageCatalogue $catalogue)
  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($fallbackCatalogue->all(), true),
  297. $currentSuffix,
  298. $fallbackSuffix
  299. );
  300. $current = $fallbackCatalogue->getLocale();
  301. $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
  302. }
  303. return $fallbackContent;
  304. }
  305. private function getCatalogueCachePath($locale)
  306. {
  307. return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
  308. }
  309. private function doLoadCatalogue($locale)
  310. {
  311. $this->catalogues[$locale] = new MessageCatalogue($locale);
  312. if (isset($this->resources[$locale])) {
  313. foreach ($this->resources[$locale] as $resource) {
  314. if (!isset($this->loaders[$resource[0]])) {
  315. throw new \RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
  316. }
  317. $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
  318. }
  319. }
  320. }
  321. private function loadFallbackCatalogues($locale)
  322. {
  323. $current = $this->catalogues[$locale];
  324. foreach ($this->computeFallbackLocales($locale) as $fallback) {
  325. if (!isset($this->catalogues[$fallback])) {
  326. $this->doLoadCatalogue($fallback);
  327. }
  328. $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
  329. $current->addFallbackCatalogue($fallbackCatalogue);
  330. $current = $fallbackCatalogue;
  331. }
  332. }
  333. protected function computeFallbackLocales($locale)
  334. {
  335. $locales = array();
  336. foreach ($this->fallbackLocales as $fallback) {
  337. if ($fallback === $locale) {
  338. continue;
  339. }
  340. $locales[] = $fallback;
  341. }
  342. if (strrchr($locale, '_') !== false) {
  343. array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
  344. }
  345. return array_unique($locales);
  346. }
  347. /**
  348. * Asserts that the locale is valid, throws an Exception if not.
  349. *
  350. * @param string $locale Locale to tests
  351. *
  352. * @throws \InvalidArgumentException If the locale contains invalid characters
  353. */
  354. protected function assertValidLocale($locale)
  355. {
  356. if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
  357. throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
  358. }
  359. }
  360. /**
  361. * Provides the ConfigCache factory implementation, falling back to a
  362. * default implementation if necessary.
  363. *
  364. * @return ConfigCacheFactoryInterface $configCacheFactory
  365. */
  366. private function getConfigCacheFactory()
  367. {
  368. if (!$this->configCacheFactory) {
  369. $this->configCacheFactory = new ConfigCacheFactory($this->debug);
  370. }
  371. return $this->configCacheFactory;
  372. }
  373. }