You are here

public function GroupMenuBlock::build in Group Menu 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/groupmenu_block/src/Plugin/Block/GroupMenuBlock.php, line 73

Class

GroupMenuBlock
Provides a block for displaying group menus.

Namespace

Drupal\groupmenu_block\Plugin\Block

Code

public function build() {

  // Get the associated group content for the current node.
  $node = $this
    ->getContextValue('node');
  if ($node) {
    $group_contents = GroupContent::loadByEntity($node);
    $menus = [];

    // Get each group this node belongs to.
    foreach ($group_contents as $group_content) {

      /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
      $group = $group_content
        ->getGroup();

      // Make an array of menus to render.
      $menus = array_merge($menus, $this
        ->getGroupMenus($group));
    }
  }
  else {

    // Not on a node page, but try to get the group anyway.
    $group = $this
      ->getContextValue('group');
    if ($group) {
      $menus = $this
        ->getGroupMenus($group);
    }
    else {
      return [];
    }
  }

  // Render the menus.
  $build = [];
  $parameters = new MenuTreeParameters();

  // Setting max depth.
  if ($max_depth = $this->configuration['max_depth']) {
    $parameters
      ->setMaxDepth($max_depth);
  }
  $parameters
    ->onlyEnabledLinks();
  $manipulators = [
    [
      'callable' => 'menu.default_tree_manipulators:checkAccess',
    ],
    [
      'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
    ],
  ];
  foreach ($menus as $menu_name => $menu) {
    $tree = \Drupal::menuTree()
      ->load($menu_name, $parameters);
    $tree = \Drupal::menuTree()
      ->transform($tree, $manipulators);
    $build[] = \Drupal::menuTree()
      ->build($tree);
  }
  return $build;
}