You are here

public function TeamContextSwitcherBlock::build in Apigee Edge 8

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

modules/apigee_edge_teams/src/Plugin/Block/TeamContextSwitcherBlock.php, line 137

Class

TeamContextSwitcherBlock
Provides a block for switching team context.

Namespace

Drupal\apigee_edge_teams\Plugin\Block

Code

public function build() {

  // Do not show a block if we do not have a corresponding route.
  if (!($current_context = $this->teamContextManager
    ->getCurrentContextEntity())) {
    return [];
  }

  // Add a link for the developer account.
  $entities = [
    $this->entityTypeManager
      ->getStorage('user')
      ->load($this->account
      ->id()),
  ];

  // Add links for teams.
  if ($team_ids = $this->teamMembershipManager
    ->getTeams($this->account
    ->getEmail())) {
    $entities = array_merge($entities, $this->entityTypeManager
      ->getStorage('team')
      ->loadMultiple($team_ids));
  }
  $links = [];

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  foreach ($entities as $entity) {

    // No link if we are on the current context route.
    if ($current_context instanceof EntityInterface && $current_context
      ->getEntityTypeId() === $entity
      ->getEntityTypeId() && $current_context
      ->id() === $entity
      ->id()) {

      // Prepend link as the first link.
      array_unshift($links, [
        'title' => $entity
          ->label(),
        'url' => Url::fromRoute('<nolink>'),
      ]);
      continue;
    }

    // Get destination link for entity.
    if (($url = $this->teamContextManager
      ->getDestinationUrlForEntity($entity)) && $url
      ->access($this->account)) {
      $links[] = [
        'title' => $entity
          ->label(),
        'url' => $url,
      ];
    }
  }

  // Add additional links.
  foreach ($this
    ->getAdditionalLinks() as $route_name => $title) {
    if (($url = Url::fromRoute($route_name)) && $url
      ->access($this->account)) {
      $links[] = [
        'title' => $title,
        'url' => $url,
      ];
    }
  }
  return count($links) ? [
    '#type' => 'dropbutton',
    '#links' => $links,
    '#attributes' => [
      'class' => [
        'team-switcher',
      ],
    ],
    '#attached' => [
      'library' => [
        'apigee_edge_teams/switcher',
      ],
    ],
  ] : [];
}