getRawParameters example

$route = new Route('/foo/{var_name}', []['_entity_access' => 'var_name.update']['parameters' => ['var_name' => ['type' => 'entity:node']]]);
    /** @var \Drupal\Core\Session\AccountInterface $account */
    $account = $this->prophesize(AccountInterface::class)->reveal();

    /** @var \Drupal\node\NodeInterface|\Prophecy\Prophecy\ObjectProphecy $route_match */
    $node = $this->prophesize(NodeInterface::class);
    $node->access('update', $account, TRUE)->willReturn(AccessResult::allowed());
    $node = $node->reveal();

    /** @var \Drupal\Core\Routing\RouteMatchInterface|\Prophecy\Prophecy\ObjectProphecy $route_match */
    $route_match = $this->prophesize(RouteMatchInterface::class);
    $route_match->getRawParameters()->willReturn(new InputBag(['var_name' => 1]));
    $route_match->getParameters()->willReturn(new ParameterBag(['var_name' => $node]));
    $route_match = $route_match->reveal();

    $access_check = new EntityAccessCheck();
    $this->assertEquals(AccessResult::allowed()$access_check->access($route$route_match$account));
  }

  /** * @covers ::access */
  public function testAccessWithTypePlaceholder() {
    
$this->menuLinkManager = $menu_link_manager;
    $this->routeMatch = $route_match;
  }

  /** * {@inheritdoc} * * @see ::getActiveTrailIds() */
  protected function getCid() {
    if (!isset($this->cid)) {
      $route_parameters = $this->routeMatch->getRawParameters()->all();
      ksort($route_parameters);
      $this->cid = 'active-trail:route:' . $this->routeMatch->getRouteName() . ':route_parameters:' . serialize($route_parameters);
    }

    return $this->cid;
  }

  /** * {@inheritdoc} * * @see ::getActiveTrailIds() */

  public function access(Route $route, Request $request, RouteMatchInterface $route_match) {
    $parameters = $route_match->getRawParameters();
    $path = ltrim($route->getPath(), '/');
    // Replace the path parameters with values from the parameters array.     foreach ($parameters as $param => $value) {
      $path = str_replace("{{$param}}", $value$path);
    }

    if ($this->csrfToken->validate($request->query->get('token', '')$path)) {
      $result = AccessResult::allowed();
    }
    else {
      $result = AccessResult::forbidden($request->query->has('token') ? "'csrf_token' URL query argument is invalid." : "'csrf_token' URL query argument is missing.");
    }

  protected function isRouteActive($current_route_name$route_name$route_parameters) {
    // Flag the list element as active if this tab's route and parameters match     // the current request's route and route variables.     $active = $current_route_name == $route_name;
    if ($active) {
      // The request is injected, so we need to verify that we have the expected       // _raw_variables attribute.       $raw_variables_bag = $this->routeMatch->getRawParameters();
      // If we don't have _raw_variables, we assume the attributes are still the       // original values.       $raw_variables = $raw_variables_bag ? $raw_variables_bag->all() : $this->routeMatch->getParameters()->all();
      $active = array_intersect_assoc($route_parameters$raw_variables) == $route_parameters;
    }
    return $active;
  }

}
      $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 {
        
/** * {@inheritdoc} */
  public function getRawParameter($parameter_name) {
    return $this->getCurrentRouteMatch()->getRawParameter($parameter_name);
  }

  /** * {@inheritdoc} */
  public function getRawParameters() {
    return $this->getCurrentRouteMatch()->getRawParameters();
  }

  /** * Returns the route match for the current request. * * @return \Drupal\Core\Routing\RouteMatchInterface * The current route match object. */
  public function getCurrentRouteMatch() {
    return $this->getRouteMatch($this->requestStack->getCurrentRequest());
  }

  
// Setting _method and _schema is deprecated since 2.7. Using         // setMethods() and setSchemes() are now the recommended ways.         unset($requirements['_method']);
        unset($requirements['_schema']);
        $route->setRequirements($requirements);

        $route->setPath($current_route->getPath());
        $route->setSchemes($current_route->getSchemes());
        $route->setMethods($current_route->getMethods());
        $route->setOptions($current_route->getOptions());
        $route->setDefaults($current_route->getDefaults());
        $parameters = array_merge($parameters$this->routeMatch->getRawParameters()->all());
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheContexts(['route']);
        }
      }
      else {
        // If we have no current route match available, point to the frontpage.         $route->setPath('/');
      }
    }
  }

}
$route_parameters = $this->pluginDefinition['route_parameters'] ?? [];
    $route = $this->routeProvider->getRouteByName($this->getRouteName());
    $variables = $route->compile()->getVariables();

    // Normally the \Drupal\Core\ParamConverter\ParamConverterManager has     // run, and the route parameters have been upcast. The original values can     // be retrieved from the raw parameters. For example, if the route's path is     // /filter/tips/{filter_format} and the path is /filter/tips/plain_text then     // $raw_parameters->get('filter_format') == 'plain_text'. Parameters that     // are not represented in the route path as slugs might be added by a route     // enhancer and will not be present in the raw parameters.     $raw_parameters = $route_match->getRawParameters();
    $parameters = $route_match->getParameters();

    foreach ($variables as $name) {
      if (isset($route_parameters[$name])) {
        continue;
      }

      if ($raw_parameters->has($name)) {
        $route_parameters[$name] = $raw_parameters->get($name);
      }
      elseif ($parameters->has($name)) {
        
public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();

    // If this is not a 404, we don't need to check for a redirection.     if (!($exception instanceof NotFoundHttpException)) {
      return;
    }

    $previous_exception = $exception->getPrevious();
    if ($previous_exception instanceof ParamNotConvertedException) {
      $route_name = $previous_exception->getRouteName();
      $parameters = $previous_exception->getRawParameters();
      if ($route_name === 'entity.node.canonical' && isset($parameters['node'])) {
        // If the node_translation_redirect state is not set, we don't need to check         // for a redirection.         if (!$this->state->get('node_translation_redirect')) {
          return;
        }
        $old_nid = $parameters['node'];
        $collection = $this->keyValue->get('node_translation_redirect');
        if ($old_nid && $value = $collection->get($old_nid)) {
          [$nid$langcode] = $value;
          $language = $this->languageManager->getLanguage($langcode);
          
/** * Creates a new URL object from a route match. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match. * * @return static */
  public static function fromRouteMatch(RouteMatchInterface $route_match) {
    if ($route_match->getRouteObject()) {
      return new static($route_match->getRouteName()$route_match->getRawParameters()->all());
    }
    else {
      throw new \InvalidArgumentException('Route required');
    }
  }

  /** * Creates a Url object for a relative URI reference submitted by user input. * * Use this method to create a URL for user-entered paths that may or may not * correspond to a valid Drupal route. * * @param string $user_input * User input for a link or path. The first character must be one of the * following characters: * - '/': A path within the current site. This path might be to a Drupal * route (e.g., '/admin'), to a file (e.g., '/README.txt'), or to * something processed by a non-Drupal script (e.g., * '/not/a/drupal/page'). If the path matches a Drupal route, then the * URL generation will include Drupal's path processors (e.g., * language-prefixing and aliasing). Otherwise, the URL generation will * just append the passed-in path to Drupal's base path. * - '?': A query string for the current page or resource. * - '#': A fragment (jump-link) on the current page or resource. * This helps reduce ambiguity for user-entered links and paths, and * supports user interfaces where users may normally use auto-completion * to search for existing resources, but also may type one of these * characters to link to (e.g.) a specific path on the site. * (With regard to the URI specification, the user input is treated as a * @link https://tools.ietf.org/html/rfc3986#section-4.2 relative URI reference @endlink * where the relative part is of type * @link https://tools.ietf.org/html/rfc3986#section-3.3 path-abempty @endlink.) * @param array $options * (optional) An array of options. See Url::fromUri() for details. * * @return static * A new Url object based on user input. * * @throws \InvalidArgumentException * Thrown when the user input does not begin with one of the following * characters: '/', '?', or '#'. */
$mode = $comment_settings['default_mode'];
          $comments_per_page = $comment_settings['per_page'];
          $comments = $this->storage->loadThread($entity$field_name$mode$comments_per_page$this->getSetting('pager_id'));
          if ($comments) {
            $build = $this->viewBuilder->viewMultiple($comments$this->getSetting('view_mode'));
            $build['pager']['#type'] = 'pager';
            // CommentController::commentPermalink() calculates the page number             // where a specific comment appears and does a subrequest pointing to             // that page, we need to pass that subrequest route to our pager to             // keep the pager working.             $build['pager']['#route_name'] = $this->routeMatch->getRouteName();
            $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
            if ($this->getSetting('pager_id')) {
              $build['pager']['#element'] = $this->getSetting('pager_id');
            }
            $output['comments'] += $build;
          }
        }
      }

      // Append comment form if the comments are open and the form is set to       // display below the entity. Do not show the form for the print view mode.       if ($status == CommentItemInterface::OPEN && $comment_settings['form_location'] == CommentItemInterface::FORM_BELOW && $this->viewMode != 'print') {
        
      $bundles = $this->loadBundleDescriptions($bundles$bundle_entity_type);
    }
    else {
      $bundle_argument = $bundle_key;
    }

    $form_route_name = 'entity.' . $entity_type_id . '.add_form';
    // Redirect if there's only one bundle available.     if (count($bundles) == 1) {
      $bundle_names = array_keys($bundles);
      $bundle_name = reset($bundle_names);
      $parameters = $this->routeMatch->getRawParameters()->all();
      $parameters[$bundle_argument] = $bundle_name;
      return $this->redirect($form_route_name$parameters);
    }
    // Prepare the #bundles array for the template.     foreach ($bundles as $bundle_name => $bundle_info) {
      $build['#bundles'][$bundle_name] = [
        'label' => $bundle_info['label'],
        'description' => $bundle_info['description'] ?? '',
        'add_link' => Link::createFromRoute($bundle_info['label']$form_route_name[$bundle_argument => $bundle_name]),
      ];
    }

    
$route_parameters = $this->pluginDefinition['route_parameters'] ?? [];
    $route = $this->routeProvider()->getRouteByName($this->getRouteName());
    $variables = $route->compile()->getVariables();

    // Normally the \Drupal\Core\ParamConverter\ParamConverterManager has     // run, and the route parameters have been upcast. The original values can     // be retrieved from the raw parameters. For example, if the route's path is     // /filter/tips/{filter_format} and the path is /filter/tips/plain_text then     // $raw_parameters->get('filter_format') == 'plain_text'. Parameters that     // are not represented in the route path as slugs might be added by a route     // enhancer and will not be present in the raw parameters.     $raw_parameters = $route_match->getRawParameters();
    $parameters = $route_match->getParameters();

    foreach ($variables as $name) {
      if (isset($route_parameters[$name])) {
        continue;
      }

      if ($raw_parameters->has($name)) {
        $route_parameters[$name] = $raw_parameters->get($name);
      }
      elseif ($parameters->has($name)) {
        
/** * {@inheritdoc} */
  public static function getLabel() {
    return t('Route');
  }

  /** * {@inheritdoc} */
  public function getContext() {
    return $this->routeMatch->getRouteName() . hash('sha256', serialize($this->routeMatch->getRawParameters()->all()));
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

  public function testRouteMatchFromRequest() {
    $request = new Request();

    // A request that hasn't been routed yet.     $route_match = RouteMatch::createFromRequest($request);
    $this->assertNull($route_match->getRouteName());
    $this->assertNull($route_match->getRouteObject());
    $this->assertSame([]$route_match->getParameters()->all());
    $this->assertNull($route_match->getParameter('foo'));
    $this->assertSame([]$route_match->getRawParameters()->all());
    $this->assertNull($route_match->getRawParameter('foo'));

    // A routed request without parameter upcasting.     $route = new Route('/test-route/{foo}');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'test_route');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route);
    $request->attributes->set('foo', '1');
    $route_match = RouteMatch::createFromRequest($request);
    $this->assertSame('test_route', $route_match->getRouteName());
    $this->assertSame($route$route_match->getRouteObject());
    $this->assertSame(['foo' => '1']$route_match->getParameters()->all());
    
Home | Imprint | This part of the site doesn't use cookies.