菜谱项目

Translator.php 12KB

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