Skip to content

Commit

Permalink
On Locale change - re init all translations in managed entities
Browse files Browse the repository at this point in the history
  • Loading branch information
Bozhidar Hristov committed Apr 3, 2017
1 parent 32d9e94 commit c09a36f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
27 changes: 20 additions & 7 deletions src/EventListener/CurrentTranslationLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class CurrentTranslationLoader implements EventSubscriber
* @var bool
*/
private $fallback = true;
/**
* @var array
*/
private $managed = [];

public function __construct(Container $container)
{
Expand All @@ -43,34 +47,41 @@ public function getSubscribedEvents()
return array('postLoad');
}

public function postLoad($Event)
public function flush()
{
foreach ($this->managed as $entity) {
$this->initializeCurrentTranslation($entity);
}
}

public function postLoad($event)
{
$Entity = $Event->getEntity();
$Entity = $event->getEntity();
if (!$Entity instanceof TranslatableInterface) {
return;
}

$this->initializeCurrentTranslation($Entity);
}

public function initializeCurrentTranslation($Entity)
public function initializeCurrentTranslation($entity)
{
$translationService = $this->container->get('object_bg.translation.service.translation');
$CurrentLanguage = $translationService->getCurrentLanguage();
$success = $this->initializeTranslation($Entity, $CurrentLanguage);
$success = $this->initializeTranslation($entity, $CurrentLanguage);

if ($success == false && $this->fallback === true) {
$this->initializeFallbackTranslation($Entity);
$this->initializeFallbackTranslation($entity);
}
}

private function initializeFallbackTranslation($Entity)
private function initializeFallbackTranslation($entity)
{
$translationService = $this->container->get('object_bg.translation.service.translation');
$fallbacks = $translationService->getFallbackLocales();

foreach ($fallbacks as $fallback) {
if ($this->initializeTranslation($Entity, $fallback)) {
if ($this->initializeTranslation($entity, $fallback)) {
break;
}
}
Expand All @@ -81,6 +92,8 @@ public function initializeTranslation($entity, $languageOrLocale)
if (!$entity instanceof TranslatableInterface) {
throw new \RuntimeException('Entity is not translatable');
}
$oid = spl_object_hash($entity);
$this->managed[$oid] = $entity;

$translationService = $this->container->get('object_bg.translation.service.translation');

Expand Down
9 changes: 9 additions & 0 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
class Translator extends OriginalTranslator
{

public function setLocale($locale)
{
$return = parent::setLocale($locale);

$this->container->get('object_bg.translation.current_translation_loader')->flush();

return $return;
}

/**
* @param string $locale
*/
Expand Down

0 comments on commit c09a36f

Please sign in to comment.