Skip to content

Commit

Permalink
Merge pull request #265 from DerekRoth/language-only-fallback
Browse files Browse the repository at this point in the history
Language only fallback
  • Loading branch information
docteurklein committed Dec 18, 2015
2 parents 328c0ec + b732655 commit 32a0227
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/Model/Translatable/TranslatableMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
}
39 changes: 39 additions & 0 deletions tests/Knp/DoctrineBehaviors/ORM/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 32a0227

Please sign in to comment.