You are here

function simple_menu_permissions_menu_link_content_create_access in Simple Menu Permissions 8

Implements hook_menu_link_content_create_access().

Check access for creating new menus.

File

./simple_menu_permissions.module, line 73
Contains simple_menu_permissions.module.

Code

function simple_menu_permissions_menu_link_content_create_access(AccountInterface $account, array $context, $entity_bundle) {
  $menu = \Drupal::routeMatch()
    ->getParameters()
    ->get('menu');

  // If the menu object can not be retrieved from the route parameters, we can try to get the menu id from the url.
  if (!$menu) {

    // Plan B. Try to get menu id from url.
    $path = \Drupal::request()
      ->getPathInfo();

    // Check if the current url matches the menu edit url pattern.
    if (fnmatch('/admin/structure/menu/manage/*', $path)) {
      $path_components = explode('/', $path);

      // Retrieve the menu id from the url.
      if (isset($path_components[5]) && is_string($path_components[5])) {

        // Try to load the menu by it's id to make sure that the menu exists.
        $menu = \Drupal::entityTypeManager()
          ->getStorage('menu')
          ->load($path_components[5]);
      }
    }
  }

  // Check if the menu could be retrieved from the route parameters
  // or that it was possible to load it by the id from the url.
  if ($menu) {
    if ($account
      ->hasPermission('add new links to ' . $menu
      ->id() . ' menu')) {
      return AccessResult::allowed();
    }
  }
  return AccessResult::forbidden();
}