Translator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. foreach ($this->catalogues[$fallback]->getResources() as $resource) {
  330. $fallbackCatalogue->addResource($resource);
  331. }
  332. $current->addFallbackCatalogue($fallbackCatalogue);
  333. $current = $fallbackCatalogue;
  334. }
  335. }
  336. protected function computeFallbackLocales($locale)
  337. {
  338. $locales = array();
  339. foreach ($this->fallbackLocales as $fallback) {
  340. if ($fallback === $locale) {
  341. continue;
  342. }
  343. $locales[] = $fallback;
  344. }
  345. if (strrchr($locale, '_') !== false) {
  346. array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
  347. }
  348. return array_unique($locales);
  349. }
  350. /**
  351. * Asserts that the locale is valid, throws an Exception if not.
  352. *
  353. * @param string $locale Locale to tests
  354. *
  355. * @throws \InvalidArgumentException If the locale contains invalid characters
  356. */
  357. protected function assertValidLocale($locale)
  358. {
  359. if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
  360. throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
  361. }
  362. }
  363. /**
  364. * Provides the ConfigCache factory implementation, falling back to a
  365. * default implementation if necessary.
  366. *
  367. * @return ConfigCacheFactoryInterface $configCacheFactory
  368. */
  369. private function getConfigCacheFactory()
  370. {
  371. if (!$this->configCacheFactory) {
  372. $this->configCacheFactory = new ConfigCacheFactory($this->debug);
  373. }
  374. return $this->configCacheFactory;
  375. }
  376. }