You are here

public function GroupMenuService::menuAccess in Group Menu 8

A custom access check for a menu operation.

Parameters

string $op: The operation to perform on the menu.

\Drupal\system\MenuInterface $menu: Run access checks for this menu object.

\Drupal\Core\Session\AccountInterface $account: Run access checks for this account.

Return value

\Drupal\Core\Access\AccessResult The access result.

Overrides GroupMenuServiceInterface::menuAccess

File

src/GroupMenuService.php, line 84

Class

GroupMenuService
Checks access for displaying menu pages.

Namespace

Drupal\groupmenu

Code

public function menuAccess($op, MenuInterface $menu, AccountInterface $account = NULL) {
  if (!isset($account)) {
    $account = $this->currentUser;
  }
  if (isset($this->menuAccess[$op][$account
    ->id()][$menu
    ->id()])) {
    return $this->menuAccess[$op][$account
      ->id()][$menu
      ->id()];
  }
  if ($account
    ->hasPermission('administer menu')) {
    return $this->menuAccess[$op][$account
      ->id()][$menu
      ->id()] = AccessResult::allowed();
  }
  $plugin_id = 'group_menu:menu';
  $group_content_types = $this->entityTypeManager
    ->getStorage('group_content_type')
    ->loadByContentPluginId($plugin_id);
  if (empty($group_content_types)) {
    return $this->menuAccess[$op][$account
      ->id()][$menu
      ->id()] = AccessResult::neutral();
  }

  // Load all the group content for this menu.
  $group_contents = $this->entityTypeManager
    ->getStorage('group_content')
    ->loadByProperties([
    'type' => array_keys($group_content_types),
    'entity_id' => $menu
      ->id(),
  ]);

  // If the menu does not belong to any group, we have nothing to say.
  if (empty($group_contents)) {
    return $this->menuAccess[$op][$account
      ->id()][$menu
      ->id()] = AccessResult::neutral();
  }

  /** @var \Drupal\group\Entity\GroupInterface[] $groups */
  $groups = [];
  foreach ($group_contents as $group_content) {

    /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
    $group = $group_content
      ->getGroup();
    $groups[$group
      ->id()] = $group;
  }

  // From this point on you need group to allow you to perform the requested
  // operation. If you are not granted access for a group, you should be
  // denied access instead.
  foreach ($groups as $group) {
    if ($group
      ->hasPermission("{$op} {$plugin_id} entity", $account)) {
      return $this->menuAccess[$op][$account
        ->id()][$menu
        ->id()] = AccessResult::allowed();
    }
  }
  return $this->menuAccess[$op][$account
    ->id()][$menu
    ->id()] = AccessResult::neutral();
}