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\Translation\Exception\InvalidArgumentException;
17 use Symfony\Component\Translation\Exception\RuntimeException;
18 use Symfony\Component\Config\ConfigCacheInterface;
19 use Symfony\Component\Config\ConfigCacheFactoryInterface;
20 use Symfony\Component\Config\ConfigCacheFactory;
25 * @author Fabien Potencier <fabien@symfony.com>
27 class Translator implements TranslatorInterface, TranslatorBagInterface
30 * @var MessageCatalogueInterface[]
32 protected $catalogues = array();
42 private $fallbackLocales = array();
45 * @var LoaderInterface[]
47 private $loaders = array();
52 private $resources = array();
55 * @var MessageSelector
70 * @var ConfigCacheFactoryInterface|null
72 private $configCacheFactory;
77 * @param string $locale The locale
78 * @param MessageSelector|null $selector The message selector for pluralization
79 * @param string|null $cacheDir The directory to use for the cache
80 * @param bool $debug Use cache in debug mode ?
82 * @throws InvalidArgumentException If a locale contains invalid characters
84 public function __construct($locale, MessageSelector $selector = null, $cacheDir = null, $debug = false)
86 $this->setLocale($locale);
87 $this->selector = $selector ?: new MessageSelector();
88 $this->cacheDir = $cacheDir;
89 $this->debug = $debug;
93 * Sets the ConfigCache factory to use.
95 * @param ConfigCacheFactoryInterface $configCacheFactory
97 public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
99 $this->configCacheFactory = $configCacheFactory;
105 * @param string $format The name of the loader (@see addResource())
106 * @param LoaderInterface $loader A LoaderInterface instance
108 public function addLoader($format, LoaderInterface $loader)
110 $this->loaders[$format] = $loader;
116 * @param string $format The name of the loader (@see addLoader())
117 * @param mixed $resource The resource name
118 * @param string $locale The locale
119 * @param string $domain The domain
121 * @throws InvalidArgumentException If the locale contains invalid characters
123 public function addResource($format, $resource, $locale, $domain = null)
125 if (null === $domain) {
126 $domain = 'messages';
129 $this->assertValidLocale($locale);
131 $this->resources[$locale][] = array($format, $resource, $domain);
133 if (in_array($locale, $this->fallbackLocales)) {
134 $this->catalogues = array();
136 unset($this->catalogues[$locale]);
143 public function setLocale($locale)
145 $this->assertValidLocale($locale);
146 $this->locale = $locale;
152 public function getLocale()
154 return $this->locale;
158 * Sets the fallback locales.
160 * @param array $locales The fallback locales
162 * @throws InvalidArgumentException If a locale contains invalid characters
164 public function setFallbackLocales(array $locales)
166 // needed as the fallback locales are linked to the already loaded catalogues
167 $this->catalogues = array();
169 foreach ($locales as $locale) {
170 $this->assertValidLocale($locale);
173 $this->fallbackLocales = $locales;
177 * Gets the fallback locales.
179 * @return array $locales The fallback locales
181 public function getFallbackLocales()
183 return $this->fallbackLocales;
189 public function trans($id, array $parameters = array(), $domain = null, $locale = null)
191 if (null === $domain) {
192 $domain = 'messages';
195 return strtr($this->getCatalogue($locale)->get((string) $id, $domain), $parameters);
201 public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
203 $parameters = array_merge(array(
204 '%count%' => $number,
207 if (null === $domain) {
208 $domain = 'messages';
212 $catalogue = $this->getCatalogue($locale);
213 $locale = $catalogue->getLocale();
214 while (!$catalogue->defines($id, $domain)) {
215 if ($cat = $catalogue->getFallbackCatalogue()) {
217 $locale = $catalogue->getLocale();
223 return strtr($this->selector->choose($catalogue->get($id, $domain), (int) $number, $locale), $parameters);
229 public function getCatalogue($locale = null)
231 if (null === $locale) {
232 $locale = $this->getLocale();
234 $this->assertValidLocale($locale);
237 if (!isset($this->catalogues[$locale])) {
238 $this->loadCatalogue($locale);
241 return $this->catalogues[$locale];
247 * @return array LoaderInterface[]
249 protected function getLoaders()
251 return $this->loaders;
255 * @param string $locale
257 protected function loadCatalogue($locale)
259 if (null === $this->cacheDir) {
260 $this->initializeCatalogue($locale);
262 $this->initializeCacheCatalogue($locale);
267 * @param string $locale
269 protected function initializeCatalogue($locale)
271 $this->assertValidLocale($locale);
274 $this->doLoadCatalogue($locale);
275 } catch (NotFoundResourceException $e) {
276 if (!$this->computeFallbackLocales($locale)) {
280 $this->loadFallbackCatalogues($locale);
284 * @param string $locale
286 private function initializeCacheCatalogue($locale)
288 if (isset($this->catalogues[$locale])) {
289 /* Catalogue already initialized. */
293 $this->assertValidLocale($locale);
294 $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
295 function (ConfigCacheInterface $cache) use ($locale) {
296 $this->dumpCatalogue($locale, $cache);
300 if (isset($this->catalogues[$locale])) {
301 /* Catalogue has been initialized as it was written out to cache. */
305 /* Read catalogue from cache. */
306 $this->catalogues[$locale] = include $cache->getPath();
309 private function dumpCatalogue($locale, ConfigCacheInterface $cache)
311 $this->initializeCatalogue($locale);
312 $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]);
314 $content = sprintf(<<<EOF
317 use Symfony\Component\Translation\MessageCatalogue;
319 \$catalogue = new MessageCatalogue('%s', %s);
327 var_export($this->catalogues[$locale]->all(), true),
331 $cache->write($content, $this->catalogues[$locale]->getResources());
334 private function getFallbackContent(MessageCatalogue $catalogue)
336 $fallbackContent = '';
338 $replacementPattern = '/[^a-z0-9_]/i';
339 $fallbackCatalogue = $catalogue->getFallbackCatalogue();
340 while ($fallbackCatalogue) {
341 $fallback = $fallbackCatalogue->getLocale();
342 $fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
343 $currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
345 $fallbackContent .= sprintf(<<<'EOF'
346 $catalogue%s = new MessageCatalogue('%s', %s);
347 $catalogue%s->addFallbackCatalogue($catalogue%s);
353 var_export($fallbackCatalogue->all(), true),
357 $current = $fallbackCatalogue->getLocale();
358 $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
361 return $fallbackContent;
364 private function getCatalogueCachePath($locale)
366 return $this->cacheDir.'/catalogue.'.$locale.'.'.sha1(serialize($this->fallbackLocales)).'.php';
369 private function doLoadCatalogue($locale)
371 $this->catalogues[$locale] = new MessageCatalogue($locale);
373 if (isset($this->resources[$locale])) {
374 foreach ($this->resources[$locale] as $resource) {
375 if (!isset($this->loaders[$resource[0]])) {
376 throw new RuntimeException(sprintf('The "%s" translation loader is not registered.', $resource[0]));
378 $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1], $locale, $resource[2]));
383 private function loadFallbackCatalogues($locale)
385 $current = $this->catalogues[$locale];
387 foreach ($this->computeFallbackLocales($locale) as $fallback) {
388 if (!isset($this->catalogues[$fallback])) {
389 $this->initializeCatalogue($fallback);
392 $fallbackCatalogue = new MessageCatalogue($fallback, $this->catalogues[$fallback]->all());
393 foreach ($this->catalogues[$fallback]->getResources() as $resource) {
394 $fallbackCatalogue->addResource($resource);
396 $current->addFallbackCatalogue($fallbackCatalogue);
397 $current = $fallbackCatalogue;
401 protected function computeFallbackLocales($locale)
404 foreach ($this->fallbackLocales as $fallback) {
405 if ($fallback === $locale) {
409 $locales[] = $fallback;
412 if (strrchr($locale, '_') !== false) {
413 array_unshift($locales, substr($locale, 0, -strlen(strrchr($locale, '_'))));
416 return array_unique($locales);
420 * Asserts that the locale is valid, throws an Exception if not.
422 * @param string $locale Locale to tests
424 * @throws InvalidArgumentException If the locale contains invalid characters
426 protected function assertValidLocale($locale)
428 if (1 !== preg_match('/^[a-z0-9@_\\.\\-]*$/i', $locale)) {
429 throw new InvalidArgumentException(sprintf('Invalid "%s" locale.', $locale));
434 * Provides the ConfigCache factory implementation, falling back to a
435 * default implementation if necessary.
437 * @return ConfigCacheFactoryInterface $configCacheFactory
439 private function getConfigCacheFactory()
441 if (!$this->configCacheFactory) {
442 $this->configCacheFactory = new ConfigCacheFactory($this->debug);
445 return $this->configCacheFactory;