You are here

function admin_toolbar_links_access_filter_filter_non_accessible_links in Admin Toolbar 8

Same name and namespace in other branches
  1. 8.2 admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module \admin_toolbar_links_access_filter_filter_non_accessible_links()
  2. 3.x admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module \admin_toolbar_links_access_filter_filter_non_accessible_links()

Hides links from admin menu, if user doesn't have access rights.

1 call to admin_toolbar_links_access_filter_filter_non_accessible_links()
admin_toolbar_links_access_filter_preprocess_menu in admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module
Implements hook_preprocess_menu().

File

admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module, line 60
This module don't show menu links that you don't have access permission for.

Code

function admin_toolbar_links_access_filter_filter_non_accessible_links(array &$items) {
  foreach ($items as $route => &$item) {
    $route_name = $route;
    $route_params = [];
    if (!empty($item['original_link'])) {

      /** @var \Drupal\Core\Menu\MenuLinkBase $original_link */
      $original_link = $item['original_link'];
      if ($original_link
        ->getUrlObject()
        ->isExternal()) {

        // Do not filter external URL at all.
        continue;
      }
      $route_name = $original_link
        ->getRouteName();
      $route_params = $original_link
        ->getRouteParameters();
    }

    // Check, if user has access rights to the route.
    if (!\Drupal::accessManager()
      ->checkNamedRoute($route_name, $route_params)) {
      unset($items[$route]);
    }
    else {
      if (!empty($items[$route]['below'])) {

        // Recursively call this function for the child items.
        admin_toolbar_links_access_filter_filter_non_accessible_links($items[$route]['below']);
      }
      if (empty($items[$route]['below']) && \Drupal::moduleHandler()
        ->moduleExists('admin_toolbar')) {

        // Every child item has been cleared out.
        // Now check, if the given route represents an overview page only,
        // without having functionality on its own. In this case, we can safely
        // unset this item, as there aren't any children left.
        // This assumption is only valid, when the admin_toolbar module is
        // installed because otherwise we won't have child items at all.
        if (admin_toolbar_links_access_filter_is_overview_page($route)) {
          unset($items[$route]);
        }
        else {

          // Let's remove the expanded flag.
          $items[$route]['is_expanded'] = FALSE;
        }
      }
    }
  }
}