vendor/terminal42/contao-changelanguage/src/Helper/AlternateLinks.php line 41

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Terminal42\ChangeLanguage\Helper;
  4. use Contao\Environment;
  5. use Contao\FrontendTemplate;
  6. use Terminal42\ChangeLanguage\Language;
  7. use Terminal42\ChangeLanguage\Navigation\NavigationItem;
  8. use Terminal42\ChangeLanguage\Navigation\UrlParameterBag;
  9. /**
  10.  * AlternateLinks is a helper class to handle <link rel="alternate"> in the page header.
  11.  */
  12. class AlternateLinks
  13. {
  14.     private array $links = [];
  15.     /**
  16.      * Returns whether a link already exists for a language.
  17.      */
  18.     public function has(string $language): bool
  19.     {
  20.         return \array_key_exists(Language::toLanguageTag($language), $this->links);
  21.     }
  22.     /**
  23.      * Adds or replaces a link for a language.
  24.      */
  25.     public function add(string $languagestring $hrefstring $title ''): void
  26.     {
  27.         $language Language::toLanguageTag($language);
  28.         $this->store($language$href$title);
  29.     }
  30.     /**
  31.      * Adds a link from a NavigationItem instance.
  32.      */
  33.     public function addFromNavigationItem(NavigationItem $itemUrlParameterBag $urlParameterBag): void
  34.     {
  35.         $this->add($item->getLanguageTag(), $item->getHref($urlParameterBag), $item->getTitle());
  36.     }
  37.     /**
  38.      * Removes link for a language if it exists.
  39.      */
  40.     public function remove(string $language): void
  41.     {
  42.         unset($this->links[Language::toLanguageTag($language)]);
  43.     }
  44.     /**
  45.      * Sets link for the x-default language.
  46.      */
  47.     public function setDefault(string $hrefstring $title ''): void
  48.     {
  49.         $this->store('x-default'$href$title);
  50.     }
  51.     /**
  52.      * Generates template markup of links for the page header.
  53.      */
  54.     public function generate(string $templateName 'block_alternate_links'): string
  55.     {
  56.         if (=== \count($this->links)) {
  57.             return '';
  58.         }
  59.         $template = new FrontendTemplate($templateName);
  60.         $template->links $this->links;
  61.         return $template->parse();
  62.     }
  63.     private function store(string $languagestring $hrefstring $title): void
  64.     {
  65.         // URLs must always be absolute
  66.         if (!== strpos($href'http://') && !== strpos($href'https://')) {
  67.             $href Environment::get('base').$href;
  68.         }
  69.         $this->links[$language] = ['language' => $language'href' => $href'title' => $title];
  70.     }
  71. }