src/Twig/Extension/LanguageSwitcherExtension.php line 42

Open in your IDE?
  1. <?php
  2.     /**
  3.      * project: Pimcore
  4.      * User: EBiermann
  5.      * Year: 2022
  6.      */
  7.     namespace App\Twig\Extension;
  8.     use Pimcore\Model\Document;
  9.     use Pimcore\Model\Document\Service;
  10.     use Pimcore\Tool;
  11.     use Twig\Extension\AbstractExtension;
  12.     use Twig\TwigFunction;
  13.     class LanguageSwitcherExtension extends AbstractExtension
  14.     {
  15.         /**
  16.          * @var Service|Service\Dao
  17.          */
  18.         private $documentService;
  19.         public function __construct(Service $documentService)
  20.         {
  21.             $this->documentService $documentService;
  22.         }
  23.         public function getLocalizedLinks(Document $document): array
  24.         {
  25.             $translations $this->documentService->getTranslations($document);
  26.             $links = [];
  27.             foreach (Tool::getValidLanguages() as $language) {
  28.                 $target '/' $language;
  29.                 //skip if root document for local is missing
  30.                 if (!(Document::getByPath($target) instanceof Document)) {
  31.                     continue;
  32.                 }
  33.                 if (isset($translations[$language])) {
  34.                     $localizedDocument Document::getById($translations[$language]);
  35.                     if ($localizedDocument) {
  36.                         $target $localizedDocument->getFullPath();
  37.                     }
  38.                 }
  39.                 $links[$language] = [
  40.                     'link'  => $target,
  41.                     'language' => $language,
  42.                     'text'  => \Locale::getDisplayLanguage($language)
  43.                 ];
  44.             }
  45.             return $links;
  46.         }
  47.         /**
  48.          * @inheritDoc
  49.          */
  50.         public function getFunctions(): array
  51.         {
  52.             return [
  53.                 new TwigFunction('get_localized_links', [$this'getLocalizedLinks'])
  54.             ];
  55.         }
  56.     }