vendor/willdurand/js-translation-bundle/Controller/Controller.php line 115

Open in your IDE?
  1. <?php
  2. namespace Bazinga\Bundle\JsTranslationBundle\Controller;
  3. use Bazinga\Bundle\JsTranslationBundle\Finder\TranslationFinder;
  4. use Bazinga\Bundle\JsTranslationBundle\Util;
  5. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  6. use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\Config\ConfigCache;
  11. use Symfony\Component\Config\Resource\FileResource;
  12. use Symfony\Component\Filesystem\Exception\IOException;
  13. use Twig\Environment;
  14. use Twig\Loader\LoaderInterface;
  15. /**
  16.  * @author William DURAND <william.durand1@gmail.com>
  17.  */
  18. class Controller
  19. {
  20.     /**
  21.      * @var TranslatorInterface
  22.      */
  23.     private $translator;
  24.     /**
  25.      * @var Environment
  26.      */
  27.     private $twig;
  28.     /**
  29.      * @var TranslationFinder
  30.      */
  31.     private $translationFinder;
  32.     /**
  33.      * @var array
  34.      */
  35.     private $loaders = array();
  36.     /**
  37.      * @var string
  38.      */
  39.     private $cacheDir;
  40.     /**
  41.      * @var boolean
  42.      */
  43.     private $debug;
  44.     /**
  45.      * @var string
  46.      */
  47.     private $localeFallback;
  48.     /**
  49.      * @var string
  50.      */
  51.     private $defaultDomain;
  52.     /**
  53.      * @var int
  54.      */
  55.     private $httpCacheTime;
  56.     /**
  57.      * @param TranslatorInterface           $translator        The translator.
  58.      * @param Environment                   $twig              The twig environment.
  59.      * @param TranslationFinder             $translationFinder The translation finder.
  60.      * @param string                        $cacheDir
  61.      * @param boolean                       $debug
  62.      * @param string                        $localeFallback
  63.      * @param string                        $defaultDomain
  64.      * @param int                           $httpCacheTime
  65.      * @throws \InvalidArgumentException
  66.      */
  67.     public function __construct(
  68.         $translator,
  69.         Environment $twig,
  70.         TranslationFinder $translationFinder,
  71.         $cacheDir,
  72.         $debug          false,
  73.         $localeFallback '',
  74.         $defaultDomain  '',
  75.         $httpCacheTime  86400
  76.     ) {
  77.         if (!$translator instanceof TranslatorInterface && !$translator instanceof LegacyTranslatorInterface) {
  78.             throw new \InvalidArgumentException(sprintf('Providing an instance of "%s" as translator is not supported.'get_class($translator)));
  79.         }
  80.         $this->translator        $translator;
  81.         $this->twig              $twig;
  82.         $this->translationFinder $translationFinder;
  83.         $this->cacheDir          $cacheDir;
  84.         $this->debug             $debug;
  85.         $this->localeFallback    $localeFallback;
  86.         $this->defaultDomain     $defaultDomain;
  87.         $this->httpCacheTime     $httpCacheTime;
  88.     }
  89.     /**
  90.      * Add a translation loader if it does not exist.
  91.      *
  92.      * @param string          $id     The loader id.
  93.      * @param LoaderInterface $loader A translation loader.
  94.      */
  95.     public function addLoader($id$loader)
  96.     {
  97.         if (!array_key_exists($id$this->loaders)) {
  98.             $this->loaders[$id] = $loader;
  99.         }
  100.     }
  101.     public function getTranslationsAction(Request $request$domain$_format)
  102.     {
  103.         $locales $this->getLocales($request);
  104.         if (=== count($locales)) {
  105.             throw new NotFoundHttpException();
  106.         }
  107.         $cache = new ConfigCache(sprintf('%s/%s.%s.%s',
  108.             $this->cacheDir,
  109.             $domain,
  110.             implode('-'$locales),
  111.             $_format
  112.         ), $this->debug);
  113.         if (!$cache->isFresh()) {
  114.             $resources    = array();
  115.             $translations = array();
  116.             foreach ($locales as $locale) {
  117.                 $translations[$locale] = array();
  118.                 $files $this->translationFinder->get($domain$locale);
  119.                 foreach ($files as $filename) {
  120.                     [$currentDomain] = Util::extractCatalogueInformationFromFilename($filename);
  121.                     if (!isset($translations[$locale][$currentDomain])) {
  122.                         $translations[$locale][$currentDomain] = array();
  123.                     }
  124.                     $extension pathinfo($filename, \PATHINFO_EXTENSION);
  125.                     if (isset($this->loaders[$extension])) {
  126.                         $resources[] = new FileResource($filename);
  127.                         $catalogue   $this->loaders[$extension]
  128.                             ->load($filename$locale$currentDomain);
  129.                         $translations[$locale][$currentDomain] = array_replace_recursive(
  130.                             $translations[$locale][$currentDomain],
  131.                             $catalogue->all($currentDomain)
  132.                         );
  133.                     }
  134.                 }
  135.             }
  136.             $content $this->twig->render('@BazingaJsTranslation/getTranslations.' $_format '.twig', array(
  137.                 'fallback'       => $this->localeFallback,
  138.                 'defaultDomain'  => $this->defaultDomain,
  139.                 'translations'   => $translations,
  140.                 'include_config' => true,
  141.             ));
  142.             try {
  143.                 $cache->write($content$resources);
  144.             } catch (IOException $e) {
  145.                 throw new NotFoundHttpException();
  146.             }
  147.         }
  148.         if (method_exists($cache'getPath')) {
  149.             $cachePath $cache->getPath();
  150.         } else {
  151.             $cachePath = (string) $cache;
  152.         }
  153.         $expirationTime = new \DateTime();
  154.         $expirationTime->modify('+' $this->httpCacheTime ' seconds');
  155.         $response = new Response(
  156.             file_get_contents($cachePath),
  157.             200,
  158.             array('Content-Type' => $request->getMimeType($_format))
  159.         );
  160.         $response->prepare($request);
  161.         $response->setPublic();
  162.         $response->setETag(md5($response->getContent()));
  163.         $response->isNotModified($request);
  164.         $response->setExpires($expirationTime);
  165.         return $response;
  166.     }
  167.     private function getLocales(Request $request)
  168.     {
  169.         if (null !== $locales $request->query->get('locales')) {
  170.             $locales explode(','$locales);
  171.         } else {
  172.             $locales = array($request->getLocale());
  173.         }
  174.         $locales array_filter($locales, function ($locale) {
  175.             return === preg_match('/^[a-z]{2,3}([-_]{1}[a-zA-Z]{2})?$/'$locale);
  176.         });
  177.         $locales array_unique(array_map(function ($locale) {
  178.             return trim($locale);
  179.         }, $locales));
  180.         return $locales;
  181.     }
  182. }