Drupal investigation

Translator.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. protected $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 locale(s).
  135. *
  136. * @param string|array $locales The fallback locale(s)
  137. *
  138. * @throws \InvalidArgumentException If a locale contains invalid characters
  139. *
  140. * @deprecated since version 2.3, to be removed in 3.0. Use setFallbackLocales() instead
  141. */
  142. public function setFallbackLocale($locales)
  143. {
  144. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the setFallbackLocales() method instead.', E_USER_DEPRECATED);
  145. $this->setFallbackLocales(is_array($locales) ? $locales : array($locales));
  146. }
  147. /**
  148. * Sets the fallback locales.
  149. *
  150. * @param array $locales The fallback locales
  151. *
  152. * @throws \InvalidArgumentException If a locale contains invalid characters
  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. public function getFallbackLocales()
  169. {
  170. return $this->fallbackLocales;
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function trans($id, array $parameters = array(), $domain = null, $locale = null)
  176. {
  177. if (null === $domain) {
  178. $domain = 'messages';
  179. }
  180. return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
  186. {
  187. if (null === $domain) {
  188. $domain = 'messages';
  189. }
  190. $id = (string) $id;
  191. $catalogue = $this->getCatalogue($locale);
  192. $locale = $catalogue->getLocale();
  193. while (!$catalogue->defines($id, $domain)) {
  194. if ($cat = $catalogue->getFallbackCatalogue()) {
  195. $catalogue = $cat;
  196. $locale = $catalogue->getLocale();
  197. } else {
  198. break;
  199. }
  200. }
  201. return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function getCatalogue($locale = null)
  207. {
  208. if (null === $locale) {
  209. $locale = $this->getLocale();
  210. } else {
  211. $this->assertValidLocale($locale);
  212. }
  213. if (!isset($this->catalogues[$locale])) {
  214. $this->loadCatalogue($locale);
  215. }
  216. return $this->catalogues[$locale];
  217. }
  218. /**
  219. * Gets the loaders.
  220. *
  221. * @return array LoaderInterface[]
  222. */
  223. protected function getLoaders()
  224. {
  225. return $this->loaders;
  226. }
  227. /**
  228. * Collects all messages for the given locale.
  229. *
  230. * @param string|null $locale Locale of translations, by default is current locale
  231. *
  232. * @return array[array] indexed by catalog
  233. *
  234. * @deprecated since version 2.8, to be removed in 3.0. Use TranslatorBagInterface::getCatalogue() method instead.
  235. */
  236. public function getMessages($locale = null)
  237. {
  238. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use TranslatorBagInterface::getCatalogue() method instead.', E_USER_DEPRECATED);
  239. $catalogue = $this->getCatalogue($locale);
  240. $messages = $catalogue->all();
  241. while ($catalogue = $catalogue->getFallbackCatalogue()) {
  242. $messages = array_replace_recursive($catalogue->all(), $messages);
  243. }
  244. return $messages;
  245. }
  246. /**
  247. * @param string $locale
  248. */
  249. protected function loadCatalogue($locale)
  250. {
  251. if (null === $this->cacheDir) {
  252. $this->initializeCatalogue($locale);
  253. } else {
  254. $this->initializeCacheCatalogue($locale);
  255. }
  256. }
  257. /**
  258. * @param string $locale
  259. */
  260. protected function initializeCatalogue($locale)
  261. {
  262. $this->assertValidLocale($locale);
  263. try {
  264. $this->doLoadCatalogue($locale);
  265. } catch (NotFoundResourceException $e) {
  266. if (!$this->computeFallbackLocales($locale)) {
  267. throw $e;
  268. }
  269. }
  270. $this->loadFallbackCatalogues($locale);
  271. }
  272. /**
  273. * @param string $locale
  274. */
  275. private function initializeCacheCatalogue($locale)
  276. {
  277. if (isset($this->catalogues[$locale])) {
  278. /* Catalogue already initialized. */
  279. return;
  280. }
  281. $this->assertValidLocale($locale);
  282. $self = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
  283. $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
  284. function (ConfigCacheInterface $cache) use ($self, $locale) {
  285. $self->dumpCatalogue($locale, $cache);
  286. }
  287. );
  288. if (isset($this->catalogues[$locale])) {
  289. /* Catalogue has been initialized as it was written out to cache. */
  290. return;
  291. }
  292. /* Read catalogue from cache. */
  293. $this->catalogues[$locale] = include $cache->getPath();
  294. }
  295. /**
  296. * This method is public because it needs to be callable from a closure in PHP 5.3. It should be made protected (or even private, if possible) in 3.0.
  297. *
  298. * @internal
  299. */
  300. public function dumpCatalogue($locale, ConfigCacheInterface $cache)
  301. {
  302. $this->initializeCatalogue($locale);
  303. $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
  304. $content = sprintf(<<<EOF
  305. <?php
  306. use Symfony\Component\Translation\MessageCatalogue;
  307. \$catalogue = new MessageCatalogue('%s', %s);
  308. %s
  309. return \$catalogue;
  310. EOF
  311. ,
  312. $locale,
  313. var_export($this->catalogues[$locale]->all(), true),
  314. $fallbackContent
  315. );
  316. $cache->write($content, $this->catalogues[$locale]->getResources());
  317. }
  318. private function getFallbackContent(MessageCatalogue $catalogue)
  319. {
  320. $fallbackContent = '';
  321. $current = '';
  322. $replacementPattern = '/[^a-z0-9_]/i';
  323. $fallbackCatalogue = $catalogue->getFallbackCatalogue();
  324. while ($fallbackCatalogue) {
  325. $fallback = $fallbackCatalogue->getLocale();
  326. $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
  327. $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
  328. $fallbackContent .= sprintf(<<<'EOF'
  329. $catalogue%s = new MessageCatalogue('%s', %s);
  330. $catalogue%s->addFallbackCatalogue($catalogue%s);
  331. EOF
  332. ,
  333. $fallbackSuffix,
  334. $fallback,
  335. var_export($fallbackCatalogue->all(), true),
  336. $currentSuffix,
  337. $fallbackSuffix
  338. );
  339. $current = $fallbackCatalogue->getLocale();
  340. $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
  341. }
  342. return $fallbackContent;
  343. }
  344. private function getCatalogueCachePath($locale)
  345. {
  346. return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
  347. }
  348. private function doLoadCatalogue($locale)
  349. {
  350. $this->catalogues[$locale] = new MessageCatalogue($locale);
  351. if (isset($this->resources[$locale])) {
  352. foreach ($this->resources[$locale] as $resource) {
  353. if (!isset($this->loaders[$resource[0]])) {
  354. throw new \RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
  355. }
  356. $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
  357. }
  358. }
  359. }
  360. private function loadFallbackCatalogues($locale)
  361. {
  362. $current = $this->catalogues[$locale];
  363. foreach ($this->computeFallbackLocales($locale) as $fallback) {
  364. if (!isset($this->catalogues[$fallback])) {
  365. $this->loadCatalogue($fallback);
  366. }
  367. $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
  368. foreach ($this->catalogues[$fallback]->getResources() as $resource) {
  369. $fallbackCatalogue->addResource($resource);
  370. }
  371. $current->addFallbackCatalogue($fallbackCatalogue);
  372. $current = $fallbackCatalogue;
  373. }
  374. }
  375. protected function computeFallbackLocales($locale)
  376. {
  377. $locales = array();
  378. foreach ($this->fallbackLocales as $fallback) {
  379. if ($fallback === $locale) {
  380. continue;
  381. }
  382. $locales[] = $fallback;
  383. }
  384. if (strrchr($locale, '_') !== false) {
  385. array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
  386. }
  387. return array_unique($locales);
  388. }
  389. /**
  390. * Asserts that the locale is valid, throws an Exception if not.
  391. *
  392. * @param string $locale Locale to tests
  393. *
  394. * @throws \InvalidArgumentException If the locale contains invalid characters
  395. */
  396. protected function assertValidLocale($locale)
  397. {
  398. if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
  399. throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
  400. }
  401. }
  402. /**
  403. * Provides the ConfigCache factory implementation, falling back to a
  404. * default implementation if necessary.
  405. *
  406. * @return ConfigCacheFactoryInterface $configCacheFactory
  407. */
  408. private function getConfigCacheFactory()
  409. {
  410. if (!$this->configCacheFactory) {
  411. $this->configCacheFactory = new ConfigCacheFactory($this->debug);
  412. }
  413. return $this->configCacheFactory;
  414. }
  415. }