You are here

public function LanguageSelectionPageConditionLanguagePrefixes::alterPageContent in Language Selection Page 8.2

Alter the $content render array used to build the LSP page.

Parameters

array &$content: The content render array.

string $destination: The destination path.

Overrides LanguageSelectionPageConditionBase::alterPageContent

File

src/Plugin/LanguageSelectionPageCondition/LanguageSelectionPageConditionLanguagePrefixes.php, line 66

Class

LanguageSelectionPageConditionLanguagePrefixes
Class for the Language Prefixes plugin.

Namespace

Drupal\language_selection_page\Plugin\LanguageSelectionPageCondition

Code

public function alterPageContent(array &$content = [], $destination = '<front>') {
  $links = [];
  $cacheable_metadata = new CacheableMetadata();
  $cacheable_metadata
    ->addCacheTags([
    'config:configurable_language_list',
    'config:language_selection_page.negotiation',
  ]);
  $cacheable_metadata
    ->addCacheContexts([
    'url',
  ]);

  // As we are generating a URL from user input, we need to catch any
  // exceptions thrown by invalid paths.
  try {

    // @todo This variable will be used in the template.
    // @todo We still have to decide what to send in it, and how.
    $links_array = [];
    foreach ($this->languageManager
      ->getNativeLanguages() as $language) {
      $url = Url::fromUserInput($destination, [
        'language' => $language,
      ]);
      $links_array[$language
        ->getId()] = [
        // We need to clone the $url object to avoid using the same one for
        // all links. When the links are rendered, options are set on the $url
        // object, so if we use the same one, they would be set for all links.
        'url' => clone $url,
        'title' => $language
          ->getName(),
        'language' => $language,
        'attributes' => [
          'class' => [
            'language-link',
          ],
        ],
      ];
    }
    foreach ($this->languageManager
      ->getNativeLanguages() as $language) {
      $url = Url::fromUserInput($destination, [
        'language' => $language,
      ]);
      $project_link = Link::fromTextAndUrl($language
        ->getName(), $url);
      $project_link = $project_link
        ->toRenderable();
      $project_link['#attributes'] = [
        'class' => [
          'language_selection_page_link_' . $language
            ->getId(),
        ],
      ];
      $links[$language
        ->getId()] = $project_link;
    }
  } catch (\InvalidArgumentException $exception) {
    $destination = '<front>';
  }
  $content[] = [
    '#theme' => 'language_selection_page_content',
    '#destination' => $destination,
    '#language_links' => [
      '#theme' => 'item_list',
      '#items' => $links,
    ],
  ];
  $cacheable_metadata
    ->applyTo($content);
}