Skip to content

Instantly share code, notes, and snippets.

@LouTerrailloune
Created April 3, 2017 11:22
Show Gist options
  • Save LouTerrailloune/c283857bcb2f53985e75c3738432f1ae to your computer and use it in GitHub Desktop.
Save LouTerrailloune/c283857bcb2f53985e75c3738432f1ae to your computer and use it in GitHub Desktop.
Symfony translation loaded from databases
<?php
namespace MainBundle\EventListener;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class TranslationListener
{
/** @var Translator */
protected $translator;
/** @var EntityManager */
protected $entityManager;
/** @var AdapterInterface */
protected $cache;
/**
* RequestListener constructor.
* @param Translator $translator
* @param EntityManager $entityManager
* @param AdapterInterface $cache
*/
public function __construct(Translator $translator, EntityManager $entityManager, AdapterInterface $cache)
{
$this->translator = $translator;
$this->entityManager = $entityManager;
$this->cache = $cache;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$catalogue = $this->translator->getCatalogue();
$translationCache = $this->cache->getItem('translations.'.$this->translator->getLocale());
if (!$translationCache->isHit())
{
// ... item does not exists in the cache
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder
->select(array('t.code', 't.domain', 'tt.text'))
->from('MainBundle:Translation', 't')
->join('t.translations', 'tt')
->where('tt.locale = :locale')
->setParameter('locale', $this->translator->getLocale())
;
$translations = $queryBuilder->getQuery()->getResult();
$dbMessages = array();
foreach($translations as $translation)
{
$dbMessages[$translation['domain']][$translation['code']] = $translation['text'];
}
$translationCache->set($dbMessages);
$translationCache->expiresAfter(3600);
$this->cache->save($translationCache);
}
else
{
$dbMessages = $translationCache->get();
}
foreach(array_keys($dbMessages) as $domain)
{
$catalogue->add($dbMessages[$domain], $domain);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment