4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Translation;
14 use Symfony\Component\Translation\Loader\LoaderInterface;
15 use Symfony\Component\Translation\Exception\NotFoundResourceException;
16 use Symfony\Component\Config\ConfigCacheInterface;
17 use Symfony\Component\Config\ConfigCacheFactoryInterface;
18 use Symfony\Component\Config\ConfigCacheFactory;
23 * @author Fabien Potencier <fabien@symfony.com>
25 class Translator implements TranslatorInterface, TranslatorBagInterface
28 * @var MessageCatalogueInterface[]
30 protected $catalogues = array();
40 private $fallbackLocales = array();
43 * @var LoaderInterface[]
45 private $loaders = array();
50 private $resources = array();
53 * @var MessageSelector
68 * @var ConfigCacheFactoryInterface|null
70 private $configCacheFactory;
75 * @param string $locale The locale
76 * @param MessageSelector|null $selector The message selector for pluralization
77 * @param string|null $cacheDir The directory to use for the cache
78 * @param bool $debug Use cache in debug mode ?
80 * @throws \InvalidArgumentException If a locale contains invalid characters
82 public function __construct($locale, MessageSelector $selector = null, $cacheDir = null, $debug = false)
84 $this->setLocale($locale);
85 $this->selector = $selector ?: new MessageSelector();
86 $this->cacheDir = $cacheDir;
87 $this->debug = $debug;
91 * Sets the ConfigCache factory to use.
93 * @param ConfigCacheFactoryInterface $configCacheFactory
95 public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
97 $this->configCacheFactory = $configCacheFactory;
103 * @param string $format The name of the loader (@see addResource())
104 * @param LoaderInterface $loader A LoaderInterface instance
106 public function addLoader($format, LoaderInterface $loader)
108 $this->loaders[$format] = $loader;
114 * @param string $format The name of the loader (@see addLoader())
115 * @param mixed $resource The resource name
116 * @param string $locale The locale
117 * @param string $domain The domain
119 * @throws \InvalidArgumentException If the locale contains invalid characters
121 public function addResource($format, $resource, $locale, $domain = null)
123 if (null === $domain) {
124 $domain = 'messages';
127 $this->assertValidLocale($locale);
129 $this->resources[$locale][] = array($format, $resource, $domain);
131 if (in_array($locale, $this->fallbackLocales)) {
132 $this->catalogues = array();
134 unset($this->catalogues[$locale]);
141 public function setLocale($locale)
143 $this->assertValidLocale($locale);
144 $this->locale = $locale;
150 public function getLocale()
152 return $this->locale;
156 * Sets the fallback locale(s).
158 * @param string|array $locales The fallback locale(s)
160 * @throws \InvalidArgumentException If a locale contains invalid characters
162 * @deprecated since version 2.3, to be removed in 3.0. Use setFallbackLocales() instead
164 public function setFallbackLocale($locales)
166 @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);
168 $this->setFallbackLocales(is_array($locales) ? $locales : array($locales));
172 * Sets the fallback locales.
174 * @param array $locales The fallback locales
176 * @throws \InvalidArgumentException If a locale contains invalid characters
178 public function setFallbackLocales(array $locales)
180 // needed as the fallback locales are linked to the already loaded catalogues
181 $this->catalogues = array();
183 foreach ($locales as $locale) {
184 $this->assertValidLocale($locale);
187 $this->fallbackLocales = $locales;
191 * Gets the fallback locales.
193 * @return array $locales The fallback locales
195 public function getFallbackLocales()
197 return $this->fallbackLocales;
203 public function trans($id, array $parameters = array(), $domain = null, $locale = null)
205 if (null === $domain) {
206 $domain = 'messages';
209 return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
215 public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
217 if (null === $domain) {
218 $domain = 'messages';
222 $catalogue = $this->getCatalogue($locale);
223 $locale = $catalogue->getLocale();
224 while (!$catalogue->defines($id, $domain)) {
225 if ($cat = $catalogue->getFallbackCatalogue()) {
227 $locale = $catalogue->getLocale();
233 return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
239 public function getCatalogue($locale = null)
241 if (null === $locale) {
242 $locale = $this->getLocale();
244 $this->assertValidLocale($locale);
247 if (!isset($this->catalogues[$locale])) {
248 $this->loadCatalogue($locale);
251 return $this->catalogues[$locale];
257 * @return array LoaderInterface[]
259 protected function getLoaders()
261 return $this->loaders;
265 * Collects all messages for the given locale.
267 * @param string|null $locale Locale of translations, by default is current locale
269 * @return array[array] indexed by catalog
271 * @deprecated since version 2.8, to be removed in 3.0. Use TranslatorBagInterface::getCatalogue() method instead.
273 public function getMessages($locale = null)
275 @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);
277 $catalogue = $this->getCatalogue($locale);
278 $messages = $catalogue->all();
279 while ($catalogue = $catalogue->getFallbackCatalogue()) {
280 $messages = array_replace_recursive($catalogue->all(), $messages);
287 * @param string $locale
289 protected function loadCatalogue($locale)
291 if (null === $this->cacheDir) {
292 $this->initializeCatalogue($locale);
294 $this->initializeCacheCatalogue($locale);
299 * @param string $locale
301 protected function initializeCatalogue($locale)
303 $this->assertValidLocale($locale);
306 $this->doLoadCatalogue($locale);
307 } catch (NotFoundResourceException $e) {
308 if (!$this->computeFallbackLocales($locale)) {
312 $this->loadFallbackCatalogues($locale);
316 * @param string $locale
318 private function initializeCacheCatalogue($locale)
320 if (isset($this->catalogues[$locale])) {
321 /* Catalogue already initialized. */
325 $this->assertValidLocale($locale);
326 $self = $this; // required for PHP 5.3 where "$this" cannot be use()d in anonymous functions. Change in Symfony 3.0.
327 $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
328 function (ConfigCacheInterface $cache) use ($self, $locale) {
329 $self->dumpCatalogue($locale, $cache);
333 if (isset($this->catalogues[$locale])) {
334 /* Catalogue has been initialized as it was written out to cache. */
338 /* Read catalogue from cache. */
339 $this->catalogues[$locale] = include $cache->getPath();
343 * 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.
347 public function dumpCatalogue($locale, ConfigCacheInterface $cache)
349 $this->initializeCatalogue($locale);
350 $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
352 $content = sprintf(<<<EOF
355 use Symfony\Component\Translation\MessageCatalogue;
357 \$catalogue = new MessageCatalogue('%s', %s);
365 var_export($this->catalogues[$locale]->all(), true),
369 $cache->write($content, $this->catalogues[$locale]->getResources());
372 private function getFallbackContent(MessageCatalogue $catalogue)
374 $fallbackContent = '';
376 $replacementPattern = '/[^a-z0-9_]/i';
377 $fallbackCatalogue = $catalogue->getFallbackCatalogue();
378 while ($fallbackCatalogue) {
379 $fallback = $fallbackCatalogue->getLocale();
380 $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
381 $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
383 $fallbackContent .= sprintf(<<<'EOF'
384 $catalogue%s = new MessageCatalogue('%s', %s);
385 $catalogue%s->addFallbackCatalogue($catalogue%s);
391 var_export($fallbackCatalogue->all(), true),
395 $current = $fallbackCatalogue->getLocale();
396 $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
399 return $fallbackContent;
402 private function getCatalogueCachePath($locale)
404 return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
407 private function doLoadCatalogue($locale)
409 $this->catalogues[$locale] = new MessageCatalogue($locale);
411 if (isset($this->resources[$locale])) {
412 foreach ($this->resources[$locale] as $resource) {
413 if (!isset($this->loaders[$resource[0]])) {
414 throw new \RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
416 $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
421 private function loadFallbackCatalogues($locale)
423 $current = $this->catalogues[$locale];
425 foreach ($this->computeFallbackLocales($locale) as $fallback) {
426 if (!isset($this->catalogues[$fallback])) {
427 $this->initializeCatalogue($fallback);
430 $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
431 foreach ($this->catalogues[$fallback]->getResources() as $resource) {
432 $fallbackCatalogue->addResource($resource);
434 $current->addFallbackCatalogue($fallbackCatalogue);
435 $current = $fallbackCatalogue;
439 protected function computeFallbackLocales($locale)
442 foreach ($this->fallbackLocales as $fallback) {
443 if ($fallback === $locale) {
447 $locales[] = $fallback;
450 if (strrchr($locale, '_') !== false) {
451 array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
454 return array_unique($locales);
458 * Asserts that the locale is valid, throws an Exception if not.
460 * @param string $locale Locale to tests
462 * @throws \InvalidArgumentException If the locale contains invalid characters
464 protected function assertValidLocale($locale)
466 if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
467 throw new \InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
472 * Provides the ConfigCache factory implementation, falling back to a
473 * default implementation if necessary.
475 * @return ConfigCacheFactoryInterface $configCacheFactory
477 private function getConfigCacheFactory()
479 if (!$this->configCacheFactory) {
480 $this->configCacheFactory = new ConfigCacheFactory($this->debug);
483 return $this->configCacheFactory;