Exemple #1
0
 /**
  * @param bool $allowCreate
  *
  * @return TranslationInterface
  */
 public function getTranslation($allowCreate = false)
 {
     $locales = $this->getLocales();
     if (empty($locales)) {
         throw new LocaleNotFoundException();
     }
     $translation = null;
     foreach ($locales as $locale) {
         if (($translation = $this->translations->get($locale)) !== null) {
             break;
         }
     }
     if ($translation === null && $allowCreate) {
         $translation = $this->getTranslationFactory()->create(['locale' => reset($locales)]);
         $this->addTranslation($translation);
     }
     if ($translation === null && $this->hasFallbackLocale()) {
         $translation = $this->translations->get($this->getFallbackLocale());
     }
     if ($translation === null) {
         if ($this->hasFallbackLocale()) {
             $locales[] = $this->getFallbackLocale();
         }
         throw new TranslationNotFoundException();
     }
     return $translation;
 }
 /**
  * {@inheritdoc}
  */
 public function translate($locale = null)
 {
     $locale = $locale ?: $this->currentLocale;
     if (null === $locale) {
         throw new \RuntimeException('No locale has been set and current locale is undefined.');
     }
     if ($this->currentTranslation && $locale === $this->currentTranslation->getLocale()) {
         return $this->currentTranslation;
     }
     if (!($translation = $this->translations->get($locale))) {
         if (null === $this->fallbackLocale) {
             throw new \RuntimeException('No fallback locale has been set.');
         }
         if (!($fallbackTranslation = $this->translations->get($this->getFallbackLocale()))) {
             $className = $this->getTranslationClass();
             $translation = new $className();
             $translation->setLocale($locale);
             $this->addTranslation($translation);
         } else {
             $translation = clone $fallbackTranslation;
         }
     }
     $this->currentTranslation = $translation;
     return $translation;
 }
 /**
  * @param string $locale
  *
  * @return TranslationInterface
  */
 public function getTranslation($locale = null)
 {
     $locale = $locale ?: $this->currentLocale;
     if (null === $locale) {
         throw new \RuntimeException('No locale has been set and current locale is undefined.');
     }
     $translation = $this->translations->get($locale);
     if (null !== $translation) {
         return $translation;
     }
     $fallbackTranslation = $this->translations->get($this->fallbackLocale);
     if (null !== $fallbackTranslation) {
         return $fallbackTranslation;
     }
     $translation = $this->createTranslation();
     $translation->setLocale($locale);
     $this->addTranslation($translation);
     return $translation;
 }