Translator.php 12 KB

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