<?php/** * Created by PhpStorm. * User: DancZer * Date: 2015.09.29. * Time: 10:06 */namespace App\AtechNet\CoreBundle\Translation;use App\AtechNet\CoreBundle\Entity\Domain;use App\AtechNet\CoreBundle\Entity\Language;use App\AtechNet\CoreBundle\Entity\Translation;use Doctrine\ORM\EntityManager;class DatabaseTranslator implements TranslatorInterface{ /** * Translator name * * @var string */ private $name; /** * @var EntityManager $entityManager */ private $entityManager; /** * @var Domain $domain */ private $domain; /** * @var Language $language */ private $language; private $memoryCache; /** * @param EntityManager $entityManager * @param int $domain_id * @param bool $warmUpCache * @throws \Exception * @internal param bool $warmupCache */ public function __construct($entityManager, int $domain_id, bool $warmUpCache = true) { $this->entityManager = $entityManager; $this->init($domain_id); if ($warmUpCache) { $this->initDomainCache(); } } private function init($domain_id) { $this->memoryCache = []; $result = $this->entityManager->createQuery('SELECT d, l, tr FROM AtechNetCoreBundle:Domain d LEFT JOIN d.language l LEFT JOIN l.translations tr WHERE d.id = :id') ->setParameter('id', $domain_id) ->getResult(); if (count($result) !== 1) { throw new \Exception('Domain not found!'); } $this->domain = $result[0]; $this->language = $this->domain->getLanguage(); $this->name = $this->domain->getName() . '_' . $this->domain->getId(); } private function initDomainCache() { /** * @var Translation $trans */ foreach ($this->domain->getLanguage()->getTranslations() as $trans) { $this->memoryCache[$trans->getKey()] = $trans->getValue(); } } /** * @inheritdoc */ public function trans($text) { $result = $this->findInCache($text); if (is_null($result)) { return $text; } elseif (!$result) { $translations = $this->findInDb($text); //not found if (!$translations) { $this->memoryCache[$text] = null; return $text; } else { /** * @var Translation $translation */ $translation = $translations[0]; $result = $translation->getValue(); $this->memoryCache[$text] = $result; return $result; } } else { return $result; } } /** * @param $text * * @return string as the translated text from memory cache or false if not found */ private function findInCache($text) { if (array_key_exists($text, $this->memoryCache)) { return $this->memoryCache[$text]; } else { return false; } } /** * @param string $text * * @return Translation $translation or false if not found */ private function findInDb($text) { return $this->entityManager->getRepository(Translation::class)->findBy([ 'language' => $this->language, 'key' => $text, ]); } public function getName() { return $this->name; }}