You are here

public function DomainNavBlock::build in Domain Access 8

Build the output.

Overrides BlockPluginInterface::build

File

domain/src/Plugin/Block/DomainNavBlock.php, line 103

Class

DomainNavBlock
Provides a block that links to all active domains.

Namespace

Drupal\domain\Plugin\Block

Code

public function build() {

  /** @var \Drupal\domain\DomainInterface $active_domain */
  $active_domain = \Drupal::service('domain.negotiator')
    ->getActiveDomain();
  $access_handler = \Drupal::entityTypeManager()
    ->getAccessControlHandler('domain');
  $account = \Drupal::currentUser();

  // Determine the visible domain list.
  $items = [];
  $add_path = $this
    ->getSetting('link_options') == 'active';

  /** @var \Drupal\domain\DomainInterface $domain */
  foreach (\Drupal::entityTypeManager()
    ->getStorage('domain')
    ->loadMultipleSorted() as $domain) {

    // Set the URL.
    if ($add_path) {
      $url = Url::fromUri($domain
        ->getUrl());
    }
    else {
      $url = Url::fromUri($domain
        ->getPath());
    }

    // Set the label text.
    $label = $domain
      ->label();
    if ($this
      ->getSetting('link_label') == 'hostname') {
      $label = $domain
        ->getHostname();
    }
    elseif ($this
      ->getSetting('link_label') == 'url') {
      $label = $domain
        ->getPath();
    }

    // Handles menu links.
    if ($domain
      ->status() || $account
      ->hasPermission('access inactive domains')) {
      if ($this
        ->getSetting('link_theme') == 'menus') {

        // @TODO: active trail isn't working properly, likely because this
        // isn't really a menu.
        $items[] = [
          'title' => $label,
          'url' => $url,
          'attributes' => [],
          'below' => [],
          'is_expanded' => FALSE,
          'is_collapsed' => FALSE,
          'in_active_trail' => $domain
            ->isActive(),
        ];
      }
      elseif ($this
        ->getSetting('link_theme') == 'select') {
        $items[] = [
          'label' => $label,
          'url' => $url
            ->toString(),
          'active' => $domain
            ->isActive(),
        ];
      }
      else {
        $items[] = [
          '#markup' => Link::fromTextAndUrl($label, $url)
            ->toString(),
        ];
      }
    }
  }

  // Set the proper theme.
  switch ($this
    ->getSetting('link_theme')) {
    case 'select':
      $build['#theme'] = 'domain_nav_block';
      $build['#items'] = $items;
      break;
    case 'menus':

      // Map the $items params to what menu.html.twig expects.
      $build['#items'] = $items;
      $build['#menu_name'] = 'domain-nav';
      $build['#sorted'] = TRUE;
      $build['#theme'] = 'menu__' . strtr($build['#menu_name'], '-', '_');
      break;
    case 'ul':
    default:
      $build['#theme'] = 'item_list';
      $build['#items'] = $items;
      break;
  }
  return $build;
}