diff --git a/src/Model/Translatable/TranslatableMethods.php b/src/Model/Translatable/TranslatableMethods.php index 13870108..f83d0dc0 100644 --- a/src/Model/Translatable/TranslatableMethods.php +++ b/src/Model/Translatable/TranslatableMethods.php @@ -103,8 +103,15 @@ protected function doTranslate($locale = null, $fallbackToDefault = true) return $translation; } - if ($fallbackToDefault && $defaultTranslation = $this->findTranslationByLocale($this->getDefaultLocale(), false)) { - return $defaultTranslation; + if ($fallbackToDefault) { + if (($fallbackLocale = $this->computeFallbackLocale($locale)) + && ($translation = $this->findTranslationByLocale($fallbackLocale))) { + return $translation; + } + + if ($defaultTranslation = $this->findTranslationByLocale($this->getDefaultLocale(), false)) { + return $defaultTranslation; + } } $class = self::getTranslationEntityClass(); @@ -208,4 +215,13 @@ protected function findTranslationByLocale($locale, $withNewTranslations = true) return $this->getNewTranslations()->get($locale); } } + + protected function computeFallbackLocale($locale) + { + if (strrchr($locale, '_') !== false) { + return substr($locale, 0, -strlen(strrchr($locale, '_'))); + } + + return false; + } } diff --git a/tests/Knp/DoctrineBehaviors/ORM/TranslatableTest.php b/tests/Knp/DoctrineBehaviors/ORM/TranslatableTest.php index 449f18b2..542067ab 100644 --- a/tests/Knp/DoctrineBehaviors/ORM/TranslatableTest.php +++ b/tests/Knp/DoctrineBehaviors/ORM/TranslatableTest.php @@ -83,6 +83,45 @@ public function should_persist_translations() ); } + /** + * @test + */ + public function should_fallback_country_locale_to_language_only_translation() + { + $em = $this->getEntityManager(); + + $entity = new \BehaviorFixtures\ORM\TranslatableEntity(); + $entity->translate('en', false)->setTitle('plastic bag'); + $entity->translate('fr', false)->setTitle('sac plastique'); + $entity->translate('fr_CH', false)->setTitle('cornet'); + $entity->mergeNewTranslations(); + + $em->persist($entity); + $em->flush(); + $id = $entity->getId(); + $em->clear(); + + $entity = $em + ->getRepository('BehaviorFixtures\ORM\TranslatableEntity') + ->find($id) + ; + + $this->assertEquals( + 'plastic bag', + $entity->translate('de')->getTitle() + ); + + $this->assertEquals( + 'sac plastique', + $entity->translate('fr_FR')->getTitle() + ); + + $this->assertEquals( + 'cornet', + $entity->translate('fr_CH')->getTitle() + ); + } + /** * @test */