/** * {@inheritdoc} */ public function getRouteParameters(RouteMatchInterface $route_match) { $parameters = isset($this->pluginDefinition['route_parameters']) ? $this->pluginDefinition['route_parameters'] : array(); $route = $this->routeProvider->getRouteByName($this->getRouteName()); $variables = $route->compile()->getVariables(); // Normally the \Drupal\Core\ParamConverter\ParamConverterManager has // processed the Request attributes, and in that case the _raw_variables // attribute holds the original path strings keyed to the corresponding // slugs in the path patterns. For example, if the route's path pattern is // /filter/tips/{filter_format} and the path is /filter/tips/plain_text then // $raw_variables->get('filter_format') == 'plain_text'. $raw_variables = $route_match->getRawParameters(); foreach ($variables as $name) { if (isset($parameters[$name])) { continue; } if ($raw_variables && $raw_variables->has($name)) { $parameters[$name] = $raw_variables->get($name); } elseif ($value = $route_match->getRawParameter($name)) { $parameters[$name] = $value; } } // The UrlGenerator will throw an exception if expected parameters are // missing. This method should be overridden if that is possible. return $parameters; }
protected function getRouteByNames(DrupalStyle $io, $route_name) { $routes = $this->routeProvider->getRoutesByNames($route_name); foreach ($routes as $name => $route) { $tableHeader = [$this->trans('commands.router.debug.messages.route'), '<info>' . $name . '</info>']; $tableRows = []; $tableRows[] = ['<comment>' . $this->trans('commands.router.debug.messages.path') . '</comment>', $route->getPath()]; $tableRows[] = ['<comment>' . $this->trans('commands.router.debug.messages.defaults') . '</comment>']; $attributes = $this->addRouteAttributes($route->getDefaults()); foreach ($attributes as $attribute) { $tableRows[] = $attribute; } $tableRows[] = ['<comment>' . $this->trans('commands.router.debug.messages.requirements') . '</comment>']; $requirements = $this->addRouteAttributes($route->getRequirements()); foreach ($requirements as $requirement) { $tableRows[] = $requirement; } $tableRows[] = ['<comment>' . $this->trans('commands.router.debug.messages.options') . '</comment>']; $options = $this->addRouteAttributes($route->getOptions()); foreach ($options as $option) { $tableRows[] = $option; } $io->table($tableHeader, $tableRows, 'compact'); } }
/** * Determines if redirect may be performed. * * @param Request $request * The current request object. * @param string $route_name * The current route name. * * @return bool * TRUE if redirect may be performed. */ public function canRedirect(Request $request, $route_name = NULL) { $can_redirect = TRUE; if (isset($route_name)) { $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { // Do not redirect if is a protected page. $can_redirect &= $this->accessManager->check($route, $request, $this->account); } } else { $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT); } if (strpos($request->getScriptName(), 'index.php') === FALSE) { // Do not redirect if the root script is not /index.php. $can_redirect = FALSE; } elseif (!($request->isMethod('GET') || $request->isMethod('HEAD'))) { // Do not redirect if this is other than GET request. $can_redirect = FALSE; } elseif ($this->state->get('system.maintenance_mode') || defined('MAINTENANCE_MODE')) { // Do not redirect in offline or maintenance mode. $can_redirect = FALSE; } elseif ($this->config->get('ignore_admin_path') && isset($route)) { // Do not redirect on admin paths. $can_redirect &= !(bool) $route->getOption('_admin_route'); } return $can_redirect; }
/** * {@inheritdoc} */ public function isValid($path) { // External URLs and the front page are always valid. if ($path == '<front>' || UrlHelper::isExternal($path)) { return TRUE; } // Check the routing system. $collection = $this->routeProvider->getRoutesByPattern('/' . $path); if ($collection->count() == 0) { return FALSE; } $request = RequestHelper::duplicate($this->requestStack->getCurrentRequest(), '/' . $path); $request->attributes->set('_system_path', $path); // We indicate that a menu administrator is running the menu access check. $request->attributes->set('_menu_admin', TRUE); // Attempt to match this path to provide a fully built request to the // access checker. try { $request->attributes->add($this->requestMatcher->matchRequest($request)); } catch (ParamNotConvertedException $e) { return FALSE; } // Consult the access manager. $routes = $collection->all(); $route = reset($routes); return $this->accessManager->check($route, $request, $this->account); }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $request = $this->requestStack->getCurrentRequest(); $page = $event->getPage(); $routes = $this->routeProvider->getRoutesByPattern($page->getPath())->all(); $route = reset($routes); if ($route && ($route_contexts = $route->getOption('parameters'))) { foreach ($route_contexts as $route_context_name => $route_context) { // Skip this parameter. if ($route_context_name == 'page_manager_page_variant' || $route_context_name == 'page_manager_page') { continue; } $context_name = $this->t('{@name} from route', ['@name' => $route_context_name]); if ($request->attributes->has($route_context_name)) { $value = $request->attributes->get($route_context_name); } else { // @todo Find a way to add in a fake value for configuration. $value = NULL; } $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['route']); $context = new Context(new ContextDefinition($route_context['type'], $context_name, FALSE), $value); $context->addCacheableDependency($cacheability); $page->addContext($route_context_name, $context); } } }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = NULL) { $this->data['routing'] = []; foreach ($this->routeProvider->getAllRoutes() as $route_name => $route) { // @TODO Find a better visual representation. $this->data['routing'][] = ['name' => $route_name, 'path' => $route->getPath()]; } }
/** * {@inheritdoc} */ public function load($menu_name, MenuTreeParameters $parameters) { $data = $this->treeStorage->loadTreeData($menu_name, $parameters); // Pre-load all the route objects in the tree for access checks. if ($data['route_names']) { $this->routeProvider->getRoutesByNames($data['route_names']); } return $this->createInstances($data['tree']); }
/** * Loads all non-admin routes right before the actual page is rendered. * * @param \Symfony\Component\HttpKernel\Event\KernelEvent $event * The event to process. */ public function onRequest(KernelEvent $event) { // Only preload on normal HTML pages, as they will display menu links. if ($this->routeProvider instanceof PreloadableRouteProviderInterface && $event->getRequest()->getRequestFormat() == 'html') { if ($routes = $this->state->get('routing.non_admin_routes', [])) { // Preload all the non-admin routes at once. $this->routeProvider->preLoadRoutes($routes); } } }
public function setUp() { $this->routeProvider = $this->getMock('Drupal\\Core\\Routing\\RouteProviderInterface'); $this->pluginDefinition = array('class' => '\\Drupal\\config_translation\\ConfigNamesMapper', 'base_route_name' => 'system.site_information_settings', 'title' => 'System information', 'names' => array('system.site'), 'weight' => 42); $this->typedConfigManager = $this->getMock('Drupal\\Core\\Config\\TypedConfigManagerInterface'); $this->localeConfigManager = $this->getMockBuilder('Drupal\\locale\\LocaleConfigManager')->disableOriginalConstructor()->getMock(); $this->configMapperManager = $this->getMock('Drupal\\config_translation\\ConfigMapperManagerInterface'); $this->baseRoute = new Route('/admin/config/system/site-information'); $this->routeProvider->expects($this->any())->method('getRouteByName')->with('system.site_information_settings')->will($this->returnValue($this->baseRoute)); $this->configNamesMapper = new TestConfigNamesMapper('system.site_information_settings', $this->pluginDefinition, $this->getConfigFactoryStub(), $this->typedConfigManager, $this->localeConfigManager, $this->configMapperManager, $this->routeProvider, $this->getStringTranslationStub()); }
public function setUp() { $this->entityManager = $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'); $this->entity = $this->getMock('Drupal\\Core\\Entity\\EntityInterface'); $this->routeProvider = $this->getMock('Drupal\\Core\\Routing\\RouteProviderInterface'); $this->routeProvider->expects($this->any())->method('getRouteByName')->with('entity.language_entity.edit_form')->will($this->returnValue(new Route('/admin/config/regional/language/edit/{language_entity}'))); $definition = array('class' => '\\Drupal\\config_translation\\ConfigEntityMapper', 'base_route_name' => 'entity.language_entity.edit_form', 'title' => '!label language', 'names' => array(), 'entity_type' => 'language_entity', 'route_name' => 'config_translation.item.overview.entity.language_entity.edit_form'); $typed_config_manager = $this->getMock('Drupal\\Core\\Config\\TypedConfigManagerInterface'); $locale_config_manager = $this->getMockBuilder('Drupal\\locale\\LocaleConfigManager')->disableOriginalConstructor()->getMock(); $this->configEntityMapper = new ConfigEntityMapper('language_entity', $definition, $this->getConfigFactoryStub(), $typed_config_manager, $locale_config_manager, $this->getMock('Drupal\\config_translation\\ConfigMapperManagerInterface'), $this->routeProvider, $this->getStringTranslationStub(), $this->entityManager); }
/** * Checks access to the route. * * @param string $route_name * The current route name. * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return bool * TRUE if access is granted. */ public function canRedirect($route_name, Request $request) { $do_redirect = TRUE; /** @var \Symfony\Component\Routing\Route $route */ $route = $this->routeProvider->getRouteByName($route_name); if ($this->config->get('access_check')) { $do_redirect &= $this->accessManager->check($route, $request, $this->account); } if ($this->config->get('ignore_admin_path')) { $do_redirect &= !(bool) $route->getOption('_admin_route'); } return $do_redirect; }
/** * {@inheritdoc} */ public function rewrite(FunctionCallNode $call, TargetInterface $target) { $arguments = $call->getArguments(); if ($arguments[0] instanceof StringNode) { $path = $arguments[0]->toValue(); // If the URL has a scheme (e.g., http://), it's external. if (parse_url($path, PHP_URL_SCHEME)) { return ClassMethodCallNode::create('\\Drupal\\Core\\Url', 'fromUri')->appendArgument(clone $arguments[0]); } elseif ($this->routeExists($path)) { $route = $this->routeProvider->getRoutesByPattern('/' . $path)->getIterator()->key(); return ClassMethodCallNode::create('\\Drupal\\Core\\Url', 'fromRoute')->appendArgument(StringNode::fromValue($route)); } } }
/** * {@inheritdoc} */ public function getActionsForRoute($route_appears) { if (!isset($this->instances[$route_appears])) { $route_names = array(); $this->instances[$route_appears] = array(); // @todo - optimize this lookup by compiling or caching. foreach ($this->getDefinitions() as $plugin_id => $action_info) { if (in_array($route_appears, $action_info['appears_on'])) { $plugin = $this->createInstance($plugin_id); $route_names[] = $plugin->getRouteName(); $this->instances[$route_appears][$plugin_id] = $plugin; } } // Pre-fetch all the action route objects. This reduces the number of SQL // queries that would otherwise be triggered by the access manager. if (!empty($route_names)) { $this->routeProvider->getRoutesByNames($route_names); } } $links = array(); /** @var $plugin \Drupal\Core\Menu\LocalActionInterface */ foreach ($this->instances[$route_appears] as $plugin_id => $plugin) { $route_name = $plugin->getRouteName(); $route_parameters = $plugin->getRouteParameters($this->routeMatch); $links[$plugin_id] = array('#theme' => 'menu_local_action', '#link' => array('title' => $this->getTitle($plugin), 'url' => Url::fromRoute($route_name, $route_parameters), 'localized_options' => $plugin->getOptions($this->routeMatch)), '#access' => $this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account), '#weight' => $plugin->getWeight()); } return $links; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $settings = $this->config('rest_api_doc.settings'); $enabled_route_names = $settings->get('routes'); $available_route_names = $this->state->get('rest_api_doc.rest_route_names'); if (empty($available_route_names)) { return array( 'no_routes' => array( '#markup' => $this->t('No REST enabled routes exist, please configure your REST end-points'), ), ); } else { $routes = $this->routeProvider->getRoutesByNames($available_route_names); $descriptions = array(); foreach ($routes as $route_name => $route) { $descriptions[$route_name] = $route_name . ' (' . $route->getPath() . ')'; } $form['routes'] = array( '#type' => 'checkboxes', '#title' => $this->t('Enabled routes'), '#description' => $this->t('Provide documentation for the following route names'), '#options' => array_combine($available_route_names, $descriptions), '#default_value' => $enabled_route_names, ); $form['overview'] = array( '#type' => 'textarea', '#default_value' => $settings->get('overview'), '#title' => $this->t('REST API overview'), '#description' => $this->t('Description to show on summary page. You may use site-wide tokens and some markup.'), ); } return parent::buildForm($form, $form_state); }
/** * Alters base_route and parent_id into the views local tasks. */ public function alterLocalTasks(&$local_tasks) { $view_route_names = $this->state->get('views.view_route_names'); foreach ($this->getApplicableMenuViews() as $pair) { list($view_id, $display_id) = $pair; /** @var $executable \Drupal\views\ViewExecutable */ $executable = $this->viewStorage->load($view_id)->getExecutable(); $executable->setDisplay($display_id); $menu = $executable->display_handler->getOption('menu'); // We already have set the base_route for default tabs. if (in_array($menu['type'], array('tab'))) { $plugin_id = 'view.' . $executable->storage->id() . '.' . $display_id; $view_route_name = $view_route_names[$executable->storage->id() . '.' . $display_id]; // Don't add a local task for views which override existing routes. if ($view_route_name != $plugin_id) { unset($local_tasks[$plugin_id]); continue; } // Find out the parent route. // @todo Find out how to find both the root and parent tab. $path = $executable->display_handler->getPath(); $split = explode('/', $path); array_pop($split); $path = implode('/', $split); $pattern = '/' . str_replace('%', '{}', $path); if ($routes = $this->routeProvider->getRoutesByPattern($pattern)) { foreach ($routes->all() as $name => $route) { $local_tasks['views_view:' . $plugin_id]['base_route'] = $name; // Skip after the first found route. break; } } } } }
/** * {@inheritdoc} */ public function getTasksBuild($current_route_name, RefinableCacheableDependencyInterface &$cacheability) { $tree = $this->getLocalTasksForRoute($current_route_name); $build = array(); // Collect all route names. $route_names = array(); foreach ($tree as $instances) { foreach ($instances as $child) { $route_names[] = $child->getRouteName(); } } // Pre-fetch all routes involved in the tree. This reduces the number // of SQL queries that would otherwise be triggered by the access manager. $routes = $route_names ? $this->routeProvider->getRoutesByNames($route_names) : array(); foreach ($tree as $level => $instances) { /** @var $instances \Drupal\Core\Menu\LocalTaskInterface[] */ foreach ($instances as $plugin_id => $child) { $route_name = $child->getRouteName(); $route_parameters = $child->getRouteParameters($this->routeMatch); // Given that the active flag depends on the route we have to add the // route cache context. $cacheability->addCacheContexts(['route']); $active = $this->isRouteActive($current_route_name, $route_name, $route_parameters); // 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); } } return $build; }
/** * {@inheritdoc} */ public function getTasksBuild($current_route_name) { $tree = $this->getLocalTasksForRoute($current_route_name); $build = array(); // Collect all route names. $route_names = array(); foreach ($tree as $instances) { foreach ($instances as $child) { $route_names[] = $child->getRouteName(); } } // Pre-fetch all routes involved in the tree. This reduces the number // of SQL queries that would otherwise be triggered by the access manager. $routes = $route_names ? $this->routeProvider->getRoutesByNames($route_names) : array(); foreach ($tree as $level => $instances) { /** @var $instances \Drupal\Core\Menu\LocalTaskInterface[] */ foreach ($instances as $plugin_id => $child) { $route_name = $child->getRouteName(); $route_parameters = $child->getRouteParameters($this->routeMatch); // Find out whether the user has access to the task. $access = $this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account); if ($access) { $active = $this->isRouteActive($current_route_name, $route_name, $route_parameters); // 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 = array('title' => $this->getTitle($child), 'url' => Url::fromRoute($route_name, $route_parameters), 'localized_options' => $child->getOptions($this->routeMatch)); $build[$level][$plugin_id] = array('#theme' => 'menu_local_task', '#link' => $link, '#active' => $active, '#weight' => $child->getWeight(), '#access' => $access); } } } return $build; }
/** * {@inheritdoc} */ public function getBaseRoute() { if ($this->routeCollection) { return $this->routeCollection->get($this->getBaseRouteName()); } else { return $this->routeProvider->getRouteByName($this->getBaseRouteName()); } }
/** * Tests the getRouteParameters method for a route with upcasted parameters. * * @covers ::getRouteParameters */ public function testGetRouteParametersForDynamicRouteWithUpcastedParameters() { $this->pluginDefinition = array('route_name' => 'test_route'); $route = new Route('/test-route/{parameter}'); $this->routeProvider->expects($this->once())->method('getRouteByName')->with('test_route')->will($this->returnValue($route)); $this->setupLocalTaskDefault(); $route_match = new RouteMatch('', $route, array('parameter' => (object) 'example2'), array('parameter' => 'example')); $this->assertEquals(array('parameter' => 'example'), $this->localTaskBase->getRouteParameters($route_match)); }
/** * Loads all non-admin routes right before the actual page is rendered. * * @param \Symfony\Component\HttpKernel\Event\KernelEvent $event * The event to process. */ public function onRequest(KernelEvent $event) { // Only preload on normal HTML pages, as they will display menu links. if ($this->routeProvider instanceof PreloadableRouteProviderInterface && $event->getRequest()->getRequestFormat() == 'html') { // Ensure that the state query is cached to skip the database query, if // possible. $key = 'routing.non_admin_routes'; if ($cache = $this->cache->get($key)) { $routes = $cache->data; } else { $routes = $this->state->get($key, []); $this->cache->set($key, $routes, Cache::PERMANENT, ['routes']); } if ($routes) { // Preload all the non-admin routes at once. $this->routeProvider->preLoadRoutes($routes); } } }
/** * Tests onRequest on a html request. */ public function testOnRequestOnHtml() { $event = $this->getMockBuilder('\\Symfony\\Component\\HttpKernel\\Event\\KernelEvent')->disableOriginalConstructor()->getMock(); $request = new Request(); $request->setRequestFormat('html'); $event->expects($this->any())->method('getRequest')->will($this->returnValue($request)); $this->routeProvider->expects($this->once())->method('preLoadRoutes')->with(['test2']); $this->state->expects($this->once())->method('get')->with('routing.non_admin_routes')->will($this->returnValue(array('test2'))); $this->preloader->onRequest($event); }
/** * {@inheritdoc} */ public function checkNamedRoute($route_name, array $parameters = array(), AccountInterface $account = NULL, $return_as_object = FALSE) { try { $route = $this->routeProvider->getRouteByName($route_name, $parameters); // ParamConverterManager relies on the route object being available // from the parameters array. $parameters[RouteObjectInterface::ROUTE_OBJECT] = $route; $upcasted_parameters = $this->paramConverterManager->convert($parameters + $route->getDefaults()); $route_match = new RouteMatch($route_name, $route, $upcasted_parameters, $parameters); return $this->check($route_match, $account, NULL, $return_as_object); } catch (RouteNotFoundException $e) { // Cacheable until extensions change. $result = AccessResult::forbidden()->addCacheTags(array('extension')); return $return_as_object ? $result : $result->isAllowed(); } catch (ParamNotConvertedException $e) { // Uncacheable because conversion of the parameter may not have been // possible due to dynamic circumstances. $result = AccessResult::forbidden()->setCacheable(FALSE); return $return_as_object ? $result : $result->isAllowed(); } }
/** * Tests the getRouteParameters method for a route with upcasted parameters. * * @see \Drupal\Core\Menu\LocalTaskDefault::getRouteParameters() */ public function testGetRouteParametersForDynamicRouteWithUpcastedParameters() { $this->pluginDefinition = array('route_name' => 'test_route'); $this->routeProvider->expects($this->once())->method('getRouteByName')->with('test_route')->will($this->returnValue(new Route('/test-route/{parameter}'))); $this->setupLocalTaskDefault(); $request = new Request(); $raw_variables = new ParameterBag(); $raw_variables->set('parameter', 'example'); $request->attributes->set('parameter', (object) array('example2')); $request->attributes->set('_raw_variables', $raw_variables); $this->assertEquals(array('parameter' => 'example'), $this->localTaskBase->getRouteParameters($request)); }
/** * Logs in a user. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * * @return \Symfony\Component\HttpFoundation\Response * A response which contains the ID and CSRF token. */ public function login(Request $request) { $format = $this->getRequestFormat($request); $content = $request->getContent(); $credentials = $this->serializer->decode($content, $format); if (!isset($credentials['name']) && !isset($credentials['pass'])) { throw new BadRequestHttpException('Missing credentials.'); } if (!isset($credentials['name'])) { throw new BadRequestHttpException('Missing credentials.name.'); } if (!isset($credentials['pass'])) { throw new BadRequestHttpException('Missing credentials.pass.'); } $this->floodControl($request, $credentials['name']); if ($this->userIsBlocked($credentials['name'])) { throw new BadRequestHttpException('The user has not been activated or is blocked.'); } if ($uid = $this->userAuth->authenticate($credentials['name'], $credentials['pass'])) { $this->flood->clear('user.http_login', $this->getLoginFloodIdentifier($request, $credentials['name'])); /** @var \Drupal\user\UserInterface $user */ $user = $this->userStorage->load($uid); $this->userLoginFinalize($user); // Send basic metadata about the logged in user. $response_data = []; if ($user->get('uid')->access('view', $user)) { $response_data['current_user']['uid'] = $user->id(); } if ($user->get('roles')->access('view', $user)) { $response_data['current_user']['roles'] = $user->getRoles(); } if ($user->get('name')->access('view', $user)) { $response_data['current_user']['name'] = $user->getAccountName(); } $response_data['csrf_token'] = $this->csrfToken->get('rest'); $logout_route = $this->routeProvider->getRouteByName('user.logout.http'); // Trim '/' off path to match \Drupal\Core\Access\CsrfAccessCheck. $logout_path = ltrim($logout_route->getPath(), '/'); $response_data['logout_token'] = $this->csrfToken->get($logout_path); $encoded_response_data = $this->serializer->encode($response_data, $format); return new Response($encoded_response_data); } $flood_config = $this->config('user.flood'); if ($identifier = $this->getLoginFloodIdentifier($request, $credentials['name'])) { $this->flood->register('user.http_login', $flood_config->get('user_window'), $identifier); } // Always register an IP-based failed login event. $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window')); throw new BadRequestHttpException('Sorry, unrecognized username or password.'); }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $request = $this->requestStack->getCurrentRequest(); $executable = $event->getPageExecutable(); $routes = $this->routeProvider->getRoutesByPattern($executable->getPage()->getPath())->all(); $route = reset($routes); if ($route_contexts = $route->getOption('parameters')) { foreach ($route_contexts as $route_context_name => $route_context) { // Skip this parameter. if ($route_context_name == 'page_manager_page') { continue; } $context_name = $this->t('{@name} from route', ['@name' => $route_context_name]); $context = new Context(new ContextDefinition($route_context['type'], $context_name)); if ($request->attributes->has($route_context_name)) { $context->setContextValue($request->attributes->get($route_context_name)); } else { // @todo Find a way to add in a fake value for configuration. } $executable->addContext($route_context_name, $context); } } }
/** * {@inheritdoc} */ protected function setUp() { $cache_contexts_manager = $this->getMockBuilder('Drupal\\Core\\Cache\\Context\\CacheContextsManager')->disableOriginalConstructor()->getMock(); $cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE); $container = new ContainerBuilder(); $container->set('cache_contexts_manager', $cache_contexts_manager); \Drupal::setContainer($container); $routes = new RouteCollection(); $first_route = new Route('/test/one'); $second_route = new Route('/test/two/{narf}'); $third_route = new Route('/test/two/'); $fourth_route = new Route('/test/four', [], [], [], '', ['https']); $none_route = new Route('', [], [], ['_no_path' => TRUE]); $routes->add('test_1', $first_route); $routes->add('test_2', $second_route); $routes->add('test_3', $third_route); $routes->add('test_4', $fourth_route); $routes->add('<none>', $none_route); // Create a route provider stub. $provider = $this->getMockBuilder('Drupal\\Core\\Routing\\RouteProvider')->disableOriginalConstructor()->getMock(); // We need to set up return value maps for both the getRouteByName() and the // getRoutesByNames() method calls on the route provider. The parameters // are not passed in and default to an empty array. $route_name_return_map = $routes_names_return_map = array(); $return_map_values = array(['route_name' => 'test_1', 'return' => $first_route], ['route_name' => 'test_2', 'return' => $second_route], ['route_name' => 'test_3', 'return' => $third_route], ['route_name' => 'test_4', 'return' => $fourth_route], ['route_name' => '<none>', 'return' => $none_route]); foreach ($return_map_values as $values) { $route_name_return_map[] = array($values['route_name'], $values['return']); $routes_names_return_map[] = array(array($values['route_name']), $values['return']); } $this->provider = $provider; $this->provider->expects($this->any())->method('getRouteByName')->will($this->returnValueMap($route_name_return_map)); $provider->expects($this->any())->method('getRoutesByNames')->will($this->returnValueMap($routes_names_return_map)); // Create an alias manager stub. $alias_manager = $this->getMockBuilder('Drupal\\Core\\Path\\AliasManager')->disableOriginalConstructor()->getMock(); $alias_manager->expects($this->any())->method('getAliasByPath')->will($this->returnCallback(array($this, 'aliasManagerCallback'))); $this->aliasManager = $alias_manager; $this->requestStack = new RequestStack(); $request = Request::create('/some/path'); $this->requestStack->push($request); $this->context = new RequestContext(); $this->context->fromRequestStack($this->requestStack); $processor = new PathProcessorAlias($this->aliasManager); $processor_manager = new PathProcessorManager(); $processor_manager->addOutbound($processor, 1000); $this->routeProcessorManager = $this->getMockBuilder('Drupal\\Core\\RouteProcessor\\RouteProcessorManager')->disableOriginalConstructor()->getMock(); $generator = new UrlGenerator($this->provider, $processor_manager, $this->routeProcessorManager, $this->requestStack, ['http', 'https']); $generator->setContext($this->context); $this->generator = $generator; }
/** * @covers ::getUrl */ public function testGetUrlWithPlaceholdersAndWithoutArgsAndExceptionValue() { $this->displayHandler->expects($this->any())->method('getRoutedDisplay')->willReturn($this->displayHandler); $this->displayHandlers->expects($this->any())->method('get')->willReturn($this->displayHandler); $this->displayHandler->expects($this->any())->method('getUrlInfo')->willReturn(Url::fromRoute('views.test.page_1')); $this->displayHandler->expects($this->any())->method('getPath')->willReturn('test-path/%/%'); $route = new Route('/test-path/{arg_0}/{arg_1}'); $this->routeProvider->expects($this->any())->method('getRouteByName')->with('views.test.page_1')->willReturn($route); $argument_handler = $this->getMockBuilder('Drupal\\views\\Plugin\\views\\argument\\ArgumentPluginBase')->disableOriginalConstructor()->getMock(); $argument_handler->options['exception']['value'] = 'exception_0'; $this->executable->argument['key_1'] = $argument_handler; $argument_handler = $this->getMockBuilder('Drupal\\views\\Plugin\\views\\argument\\ArgumentPluginBase')->disableOriginalConstructor()->getMock(); $argument_handler->options['exception']['value'] = 'exception_1'; $this->executable->argument['key_2'] = $argument_handler; $this->assertEquals(Url::fromRoute('views.test.page_1', ['arg_0' => 'exception_0', 'arg_1' => 'exception_1']), $this->executable->getUrl()); }
/** * Checks a named route with parameters against applicable access check services. * * Determines whether the route is accessible or not. * * @param string $route_name * The route to check access to. * @param array $parameters * Optional array of values to substitute into the route path patern. * @param \Drupal\Core\Session\AccountInterface $account * The current user. * @param \Symfony\Component\HttpFoundation\Request $route_request * Optional incoming request object. If not provided, one will be built * using the route information and the current request from the container. * * @return bool * Returns TRUE if the user has access to the route, otherwise FALSE. */ public function checkNamedRoute($route_name, array $parameters = array(), AccountInterface $account, Request $route_request = NULL) { try { $route = $this->routeProvider->getRouteByName($route_name, $parameters); if (empty($route_request)) { // Create a request and copy the account from the current request. $defaults = $parameters + $route->getDefaults(); $route_request = RequestHelper::duplicate($this->requestStack->getCurrentRequest(), $this->urlGenerator->generate($route_name, $defaults)); $defaults[RouteObjectInterface::ROUTE_OBJECT] = $route; $route_request->attributes->add($this->paramConverterManager->convert($defaults, $route_request)); } return $this->check($route, $route_request, $account); } catch (RouteNotFoundException $e) { return FALSE; } catch (ParamNotConvertedException $e) { return FALSE; } }
/** * {@inheritdoc} */ public function getActionsForRoute($route_appears) { if (!isset($this->instances[$route_appears])) { $route_names = array(); $this->instances[$route_appears] = array(); // @todo - optimize this lookup by compiling or caching. foreach ($this->getDefinitions() as $plugin_id => $action_info) { if (in_array($route_appears, $action_info['appears_on'])) { $plugin = $this->createInstance($plugin_id); $route_names[] = $plugin->getRouteName(); $this->instances[$route_appears][$plugin_id] = $plugin; } } // Pre-fetch all the action route objects. This reduces the number of SQL // queries that would otherwise be triggered by the access manager. if (!empty($route_names)) { $this->routeProvider->getRoutesByNames($route_names); } } $links = array(); /** @var $plugin \Drupal\Core\Menu\LocalActionInterface */ foreach ($this->instances[$route_appears] as $plugin_id => $plugin) { $cacheability = new CacheableMetadata(); $route_name = $plugin->getRouteName(); $route_parameters = $plugin->getRouteParameters($this->routeMatch); $access = $this->accessManager->checkNamedRoute($route_name, $route_parameters, $this->account, TRUE); $links[$plugin_id] = array('#theme' => 'menu_local_action', '#link' => array('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); // For backward compatibility in 8.0.x, plugins that do not implement // the \Drupal\Core\Cache\CacheableDependencyInterface are assumed // to be cacheable forever. if ($plugin instanceof CacheableDependencyInterface) { $cacheability->addCacheableDependency($plugin); } else { $cacheability->setCacheMaxAge(Cache::PERMANENT); } $cacheability->applyTo($links[$plugin_id]); } $links['#cache']['contexts'][] = 'route'; return $links; }
/** * {@inheritdoc} */ public function checkNamedRoute($route_name, array $parameters = array(), AccountInterface $account, Request $route_request = NULL) { try { $route = $this->routeProvider->getRouteByName($route_name, $parameters); if (empty($route_request)) { // Create a cloned request with fresh attributes. $route_request = RequestHelper::duplicate($this->requestStack->getCurrentRequest(), $this->urlGenerator->generate($route_name, $parameters)); $route_request->attributes->replace(array()); // Populate $route_request->attributes with both raw and converted // parameters. $parameters += $route->getDefaults(); $route_request->attributes->set('_raw_variables', new ParameterBag($parameters)); $parameters[RouteObjectInterface::ROUTE_OBJECT] = $route; $route_request->attributes->add($this->paramConverterManager->convert($parameters, $route_request)); } return $this->check($route, $route_request, $account); } catch (RouteNotFoundException $e) { return FALSE; } catch (ParamNotConvertedException $e) { return FALSE; } }