checkNamedRoute example

/** * Checks access to the link route. * * @param \Drupal\views\ResultRow $row * A view result row. * * @return \Drupal\Core\Access\AccessResultInterface|null * The access result, or NULL if the URI elements of the link doesn't exist. */
  protected function checkUrlAccess(ResultRow $row) {
    if ($url = $this->getUrlInfo($row)) {
      return $this->accessManager->checkNamedRoute($url->getRouteName()$url->getRouteParameters()$this->currentUser(), TRUE);
    }
  }

  /** * Returns the URI elements of the link. * * @param \Drupal\views\ResultRow $row * A view result row. * * @return \Drupal\Core\Url|null * The URI elements of the link. */

  public function access(AccountInterface $account = NULL, $return_as_object = FALSE) {
    if ($this->isRouted()) {
      return $this->accessManager()->checkNamedRoute($this->getRouteName()$this->getRouteParameters()$account$return_as_object);
    }
    return $return_as_object ? AccessResult::allowed() : TRUE;
  }

  /** * Checks a URL render element against applicable access check services. * * @param array $element * A render element as returned from \Drupal\Core\Url::toRenderArray(). * * @return bool * Returns TRUE if the current user has access to the URL, otherwise FALSE. * * @deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. There is no * replacement. * * @see https://www.drupal.org/node/3342977 */

  public function getContextualLinksArrayByGroup($group_name, array $route_parameters, array $metadata = []) {
    $links = [];
    $request = $this->requestStack->getCurrentRequest();
    foreach ($this->getContextualLinkPluginsByGroup($group_name) as $plugin_id => $plugin_definition) {
      /** @var \Drupal\Core\Menu\ContextualLinkInterface $plugin */
      $plugin = $this->createInstance($plugin_id);
      $route_name = $plugin->getRouteName();

      // Check access.       if (!$this->accessManager->checkNamedRoute($route_name$route_parameters$this->account)) {
        continue;
      }

      $links[$plugin_id] = [
        'route_name' => $route_name,
        'route_parameters' => $route_parameters,
        'title' => $plugin->getTitle($request),
        'weight' => $plugin->getWeight(),
        'localized_options' => $plugin->getOptions(),
        'metadata' => $metadata,
      ];
    }
// The plugin may have been set active in getLocalTasksForRoute() if         // one of its child tabs is the active tab.         $active = $active || $child->getActive();
        // @todo It might make sense to use link render elements instead.
        $link = [
          'title' => $this->getTitle($child),
          'url' => Url::fromRoute($route_name$route_parameters),
          'localized_options' => $child->getOptions($this->routeMatch),
        ];
        $access = $this->accessManager->checkNamedRoute($route_name$route_parameters$this->account, TRUE);
        $build[$level][$plugin_id] = [
          '#theme' => 'menu_local_task',
          '#link' => $link,
          '#active' => $active,
          '#weight' => $child->getWeight(),
          '#access' => $access,
        ];
        $cacheability->addCacheableDependency($access)->addCacheableDependency($child);
      }
    }

    

  public function getRouteLink(string $text, string $route, array $parameters = [], array $options = []): array {
    assert($this->accessManager instanceof AccessManagerInterface, "The access manager hasn't been set up. Any configuration YAML file with a service directive dealing with the Twig configuration can cause this, most likely found in a recently installed or changed module.");

    $bubbles = new BubbleableMetadata();
    $bubbles->addCacheTags(['route_match']);

    try {
      $access_object = $this->accessManager->checkNamedRoute($route$parameters, NULL, TRUE);
      $bubbles->addCacheableDependency($access_object);

      if ($access_object->isAllowed()) {
        $options['absolute'] = TRUE;
        $url = Url::fromRoute($route$parameters$options);
        // Generate the URL to check for parameter problems and collect         // cache metadata.         $generated = $url->toString(TRUE);
        $bubbles->addCacheableDependency($generated);
        $build = [
          '#title' => $text,
          
$container->get('access_manager'),
      $container->get('current_user')
    );
  }

  /** * {@inheritdoc} */
  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      /** @var \Drupal\Core\Access\AccessResultInterface|\Drupal\Core\Cache\CacheableDependencyInterface $access_result */
      $access_result = $this->accessManager->checkNamedRoute('block_content.add_page', []$this->currentUser, TRUE);
      $element = [
        '#markup' => $this->t('Add a <a href=":url">content block</a>.', [':url' => Url::fromRoute('block_content.add_page')->toString()]),
        '#access' => $access_result->isAllowed(),
        '#cache' => [
          'contexts' => $access_result->getCacheContexts(),
          'tags' => $access_result->getCacheTags(),
          'max-age' => $access_result->getCacheMaxAge(),
        ],
      ];
      return $element;
    }
    
case 'update':
        if (!$account->hasPermission('administer menu')) {
          return AccessResult::neutral("The 'administer menu' permission is required.")->cachePerPermissions();
        }
        else {
          // Assume that access is allowed.           $access = AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
          /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
          // If the link is routed determine whether the user has access unless           // they have the 'link to any page' permission.           if (!$account->hasPermission('link to any page') && ($url_object = $entity->getUrlObject()) && $url_object->isRouted()) {
            $link_access = $this->accessManager->checkNamedRoute($url_object->getRouteName()$url_object->getRouteParameters()$account, TRUE);
            $access = $access->andIf($link_access);
          }
          return $access;
        }

      case 'delete':
        return AccessResult::allowedIfHasPermission($account, 'administer menu')
          ->andIf(AccessResult::allowedIf(!$entity->isNew())->addCacheableDependency($entity));

      default:
        return parent::checkAccess($entity$operation$account);
    }
      if (!empty($route_names)) {
        $this->routeProvider->getRoutesByNames($route_names);
      }
    }
    $links = [];
    $cacheability = new CacheableMetadata();
    $cacheability->addCacheContexts(['route']);
    /** @var \Drupal\Core\Menu\LocalActionInterface $plugin */
    foreach ($this->instances[$route_appears] as $plugin_id => $plugin) {
      $route_name = $plugin->getRouteName();
      $route_parameters = $plugin->getRouteParameters($this->routeMatch);
      $access = $this->accessManager->checkNamedRoute($route_name$route_parameters$this->account, TRUE);
      $links[$plugin_id] = [
        '#theme' => 'menu_local_action',
        '#link' => [
          'title' => $this->getTitle($plugin),
          'url' => Url::fromRoute($route_name$route_parameters),
          'localized_options' => $plugin->getOptions($this->routeMatch),
        ],
        '#access' => $access,
        '#weight' => $plugin->getWeight(),
      ];
      $cacheability->addCacheableDependency($access)->addCacheableDependency($plugin);
    }

  protected function makeSubrequestToCustomPath(ExceptionEvent $event$custom_path$status_code) {
    $url = Url::fromUserInput($custom_path);
    if ($url->isRouted()) {
      $access_result = $this->accessManager->checkNamedRoute($url->getRouteName()$url->getRouteParameters(), NULL, TRUE);
      $request = $event->getRequest();

      // Merge the custom path's route's access result's cacheability metadata       // with the existing one (from the master request), otherwise create it.       if (!$request->attributes->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
        $request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
      }
      else {
        $existing_access_result = $request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT);
        if ($existing_access_result instanceof RefinableCacheableDependencyInterface) {
          $existing_access_result->addCacheableDependency($access_result);
        }
$this->checkProvider->setChecks($this->routeCollection);
    $this->setupAccessArgumentsResolverFactory();

    $this->paramConverter->expects($this->exactly(4))
      ->method('convert')
      ->willReturnMap([
        [[RouteObjectInterface::ROUTE_NAME => 'test_route_2', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_2')][]],
        [['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_4', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_4')]['value' => 'example']],
      ]);

    // Tests the access with routes with parameters without given request.     $this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_2', []$this->account));
    $this->assertEquals(AccessResult::allowed()$this->accessManager->checkNamedRoute('test_route_2', []$this->account, TRUE));
    $this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_4', ['value' => 'example']$this->account));
    $this->assertEquals(AccessResult::allowed()$this->accessManager->checkNamedRoute('test_route_4', ['value' => 'example']$this->account, TRUE));
  }

  /** * Tests the checkNamedRoute with upcasted values. * * @see \Drupal\Core\Access\AccessManager::checkNamedRoute() */
  public function testCheckNamedRouteWithUpcastedValues() {
    
$this->messenger()
      ->addStatus($this->t('Revision from %revision-date of @type %title has been deleted.', [
        '%revision-date' => $this->dateFormatter->format($this->revision->getRevisionCreationTime()),
        '@type' => $node_type,
        '%title' => $this->revision->label(),
      ]));
    // Set redirect to the revisions history page.     $route_name = 'entity.node.version_history';
    $parameters = ['node' => $this->revision->id()];
    // If no revisions found, or the user does not have access to the revisions     // page, then redirect to the canonical node page instead.     if (!$this->accessManager->checkNamedRoute($route_name$parameters) || count($this->nodeStorage->revisionIds($this->revision)) === 1) {
      $route_name = 'entity.node.canonical';
    }
    $form_state->setRedirect($route_name$parameters);
  }

}
      $fake_route_match = RouteMatch::createFromRequest($fake_request);
      $mapper->populateFromRouteMatch($fake_route_match);
      $mapper->setLangcode($langcode);

      // Prepare the language name and the operations depending on whether this       // is the original language or not.       if ($langcode == $original_langcode) {
        $language_name = '<strong>' . $this->t('@language (original)', ['@language' => $language->getName()]) . '</strong>';

        // Check access for the path/route for editing, so we can decide to         // include a link to edit or not.         $edit_access = $this->accessManager->checkNamedRoute($mapper->getBaseRouteName()$route_match->getRawParameters()->all()$this->account);

        // Build list of operations.         $operations = [];
        if ($edit_access) {
          $operations['edit'] = [
            'title' => $this->t('Edit'),
            'url' => Url::fromRoute($mapper->getBaseRouteName()$mapper->getBaseRouteParameters()['query' => ['destination' => $mapper->getOverviewPath()]]),
          ];
        }
      }
      else {
        
public function render($empty = FALSE) {
    $account = \Drupal::currentUser();
    if (!$empty || !empty($this->options['empty'])) {
      $element = [
        '#theme' => 'links',
        '#links' => [
          [
            'url' => Url::fromRoute('node.add_page'),
            'title' => $this->t('Add content'),
          ],
        ],
        '#access' => $this->accessManager->checkNamedRoute('node.add_page', []$account),
      ];
      return $element;
    }
    return [];
  }

}
$access = FALSE;

    if (!empty($element['#autocomplete_route_name'])) {
      $parameters = $element['#autocomplete_route_parameters'] ?? [];
      $options = [];
      if (!empty($element['#autocomplete_query_parameters'])) {
        $options['query'] = $element['#autocomplete_query_parameters'];
      }
      $url = Url::fromRoute($element['#autocomplete_route_name']$parameters$options)->toString(TRUE);
      /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
      $access_manager = \Drupal::service('access_manager');
      $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name']$parameters, \Drupal::currentUser(), TRUE);
    }

    if ($access) {
      $metadata = BubbleableMetadata::createFromRenderArray($element);
      if ($access->isAllowed()) {
        $element['#attributes']['class'][] = 'form-autocomplete';
        $metadata->addAttachments(['library' => ['core/drupal.autocomplete']]);
        // Provide a data attribute for the JavaScript behavior to bind to.         $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
        $metadata = $metadata->merge($url);
      }
      
$row['links']['permissions'] = [
        '#type' => 'link',
        '#title' => $this->t('Permissions <span class="visually-hidden">for @module</span>', ['@module' => $module->info['name']]),
        '#url' => Url::fromRoute('user.admin_permissions.module', ['modules' => $module->getName()]),
        '#options' => ['attributes' => ['class' => ['module-link', 'module-link-permissions']]],
      ];
    }

    // Generate link for module's configuration page, if it has one.     if ($module->status && isset($module->info['configure'])) {
      $route_parameters = $module->info['configure_parameters'] ?? [];
      if ($this->accessManager->checkNamedRoute($module->info['configure']$route_parameters$this->currentUser)) {
        $row['links']['configure'] = [
          '#type' => 'link',
          '#title' => $this->t('Configure <span class="visually-hidden">@module</span>', ['@module' => $module->info['name']]),
          '#url' => Url::fromRoute($module->info['configure']$route_parameters),
          '#options' => [
            'attributes' => [
              'class' => ['module-link', 'module-link-configure'],
            ],
          ],
        ];
      }
    }
Home | Imprint | This part of the site doesn't use cookies.