You are here

public function LanguageDropdownBlock::build in Language Switcher Dropdown 8.2

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/LanguageDropdownBlock.php, line 686

Class

LanguageDropdownBlock
Provides a 'Language dropdown switcher' block.

Namespace

Drupal\lang_dropdown\Plugin\Block

Code

public function build() {
  $library = [];
  switch ($this->configuration['widget']) {
    case LANGDROPDOWN_MSDROPDOWN:
      $library = $this->libraryDiscovery
        ->getLibraryByName('lang_dropdown', 'ms-dropdown');
      break;
    case LANGDROPDOWN_CHOSEN:
      $library = $this->libraryDiscovery
        ->getLibraryByName('lang_dropdown', 'chosen');
      break;
    case LANGDROPDOWN_DDSLICK:
      $library = $this->libraryDiscovery
        ->getLibraryByName('lang_dropdown', 'ddslick');
      break;
  }
  if (empty($library) && $this->configuration['widget'] != LANGDROPDOWN_SIMPLE_SELECT) {
    return [];
  }
  $route = $this->pathMatcher
    ->isFrontPage() ? '<front>' : '<current>';
  $url = Url::fromRoute($route);
  list(, $type) = explode(':', $this
    ->getPluginId());

  /** @var \stdClass $languages */
  $languages = $this->languageManager
    ->getLanguageSwitchLinks($type, $url);
  $roles = $this->currentUser
    ->getRoles();
  foreach ($languages->links as $langcode => $link) {
    $hide_language = TRUE;
    foreach ($roles as $role) {
      if (!isset($this->configuration['hidden_languages'][$role]) || !in_array($langcode, $this->configuration['hidden_languages'][$role], FALSE)) {
        $hide_language = FALSE;
        break;
      }
    }
    if ($hide_language) {
      unset($languages->links[$langcode]['href']);
      $languages->links[$langcode]['attributes']['class'][] = 'locale-untranslated';
    }
    $languages->links[$langcode]['language'] = $this->languageManager
      ->getLanguage($langcode);
  }
  if (empty($languages->links)) {
    return [];
  }
  $form = $this->formBuilder
    ->getForm(LanguageDropdownForm::class, $languages->links, $type, $this->configuration);
  return [
    'lang_dropdown_form' => $form,
    '#cache' => [
      'max-age' => 0,
    ],
  ];
}