PageRenderTime 38ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/Translation/Translator.php

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