/** * Build block library for a content entity. * * @param RouteMatch $route_match * The route match object. * * @return array */ public function contentBlockLibrary(RouteMatch $route_match) { $parameters = $route_match->getParameters(); $entity_type_id = $parameters->get('entity_type_id'); /** @var ContentEntityInterface $content_entity */ $content_entity = $parameters->get($entity_type_id); $entity_layout = $this->entityLayoutManager->getEntityLayout($entity_type_id, $content_entity->bundle()); return $this->buildBlockLibrary($entity_layout, $content_entity); }
public function access(Route $route, RouteMatch $match, AccountInterface $account) { $tempstore_id = $route->getDefault('tempstore_id'); $id = $match->getParameter($route->getRequirement('_ctools_access')); if ($tempstore_id && $id) { $cached_values = $this->getTempstore()->get($tempstore_id)->get($id); if (!empty($cached_values['access']) && $cached_values['access'] instanceof CToolsAccessInterface) { return $cached_values['access']->access($account); } } return AccessResult::forbidden(); }
/** * @covers ::createFromRequest * @covers ::__construct */ 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(array(), $route_match->getParameters()->all()); $this->assertNull($route_match->getParameter('foo')); $this->assertSame(array(), $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(array('foo' => '1'), $route_match->getParameters()->all()); $this->assertSame(array(), $route_match->getRawParameters()->all()); // A routed request with parameter upcasting. $foo = new \stdClass(); $foo->value = 1; $request->attributes->set('foo', $foo); $request->attributes->set('_raw_variables', new ParameterBag(array('foo' => '1'))); $route_match = RouteMatch::createFromRequest($request); $this->assertSame(array('foo' => $foo), $route_match->getParameters()->all()); $this->assertSame(array('foo' => '1'), $route_match->getRawParameters()->all()); }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } if ($this->account->isAnonymous() && $path == 'user') { // Forward anonymous user to login page. $event->setResponse(new RedirectResponse($this->url('user.login', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If user is logged in, redirect to 'user' instead of giving 403. $event->setResponse(new RedirectResponse($this->url('user.page', [], ['absolute' => TRUE]))); return; } if ($path == 'user/register') { // Authenticated user should be redirected to user edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If the user is already logged in, redirect to their profile page. $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()])); return; } if ($path == 'user/register') { // If the user is already registered, redirect to their edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $route_match = RouteMatch::createFromRequest($event->getRequest()); if ($this->maintenanceMode->applies($route_match)) { if (!$this->maintenanceMode->exempt($this->account)) { // Deliver the 503 page if the site is in maintenance mode and the // logged in user is not allowed to bypass it. drupal_maintenance_theme(); $content = Xss::filterAdmin(String::format($this->config->get('system.maintenance')->get('message'), array('@site' => $this->config->get('system.site')->get('name')))); // @todo Break the dependency on DefaultHtmlPageRenderer, see: // https://www.drupal.org/node/2295609 $content = DefaultHtmlPageRenderer::renderPage($content, $this->t('Site under maintenance')); $response = new Response('Service unavailable', 503); $response->setContent($content); $event->setResponse($response); } else { // Display a message if the logged in user has access to the site in // maintenance mode. However, suppress it on the maintenance mode // settings page. if ($route_match->getRouteName() != 'system.site_maintenance_mode') { if ($this->account->hasPermission('administer site configuration')) { $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE); } else { $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE); } } } } }
/** * Redirects anonymous users from user.page to user.login. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The event to process. */ public function onException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException) { $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName(); if ($route_name == 'user.page' && !$this->account->isAuthenticated()) { $event->setResponse($this->redirect('user.login')); } } }
public function access(Route $route, RouteMatch $match, AccountInterface $account) { $tempstore_id = $match->getParameter('tempstore_id') ? $match->getParameter('tempstore_id') : $route->getDefault('tempstore_id'); $id = $match->getParameter($route->getRequirement('_ctools_access')); if ($tempstore_id && $id) { $cached_values = $this->getTempstore()->get($tempstore_id)->get($id); if (!empty($cached_values['access']) && $cached_values['access'] instanceof CToolsAccessInterface) { $access = $cached_values['access']->access($account); } else { $access = AccessResult::allowed(); } } else { $access = AccessResult::forbidden(); } // The different wizards will have different tempstore ids and adding this // cache context allows us to nuance the access per wizard. $access->addCacheContexts(['url.query_args:tempstore_id']); return $access; }
/** * Initializes the theme system after the routing system. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The Event to process. */ public function onKernelRequestThemeNegotiator(GetResponseEvent $event) { if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) { if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { // @todo Refactor drupal_theme_initialize() into a request subscriber. // @see https://drupal.org/node/2228093 drupal_theme_initialize(RouteMatch::createFromRequest($event->getRequest())); } } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, RouteMatch $routeMatch = NULL) { $pbid = NULL; if ($routeMatch->getRouteName() == 'd8phonebook.edit') { // If we're on an edit URL, try to retrieve the phonebook entry by its ID. $pbid = $routeMatch->getParameter('phonebook'); $query = $this->connection->select('phonebook', 'p')->fields('p'); $query->condition('pbid', $pbid); $entry = $query->execute()->fetchObject(); if (!$entry) { // Return 404 if the entry is not found. throw new NotFoundHttpException(); } } // Push the phonebook entry ID to the submit handler. $form['pbid'] = ['#type' => 'value', '#value' => $pbid]; $form['name'] = ['#type' => 'textfield', '#title' => $this->t('Name'), '#maxlength' => 64, '#default_value' => $pbid ? $entry->name : '']; $form['phone'] = ['#type' => 'textfield', '#title' => $this->t('Phone'), '#maxlength' => 64, '#default_value' => $pbid ? $entry->phone : '']; $form['actions'] = ['#type' => 'actions', 'save' => ['#type' => 'submit', '#value' => $this->t('Save')]]; return $form; }
/** * Logout users if site is in maintenance mode. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse($this->redirect($this->url('<front>'))); } } }
/** * Delete a phonebook entry. * * @param \Drupal\Core\Routing\RouteMatch $routeMatch */ public function delete(RouteMatch $routeMatch) { // CSRF is already checked by the routing system, so we're only making sure // that an existing item is being deleted. $pbid = $routeMatch->getParameter('phonebook'); $query = $this->connection->select('phonebook', 'p')->fields('p', ['name']); $query->condition('pbid', $pbid); $entry = $query->execute()->fetchObject(); if (!$entry) { // Return a 404 if the entry is not found. throw new NotFoundHttpException(); } $this->connection->delete('phonebook')->condition('pbid', $pbid)->execute(); drupal_set_message($this->t('Deleted entry for %name.', ['%name' => $entry->name])); return new RedirectResponse('/phonebook'); }
/** * Redirects users when access is denied. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The event to process. */ public function onException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException) { $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName(); if ($this->account->isAuthenticated()) { switch ($route_name) { case 'user.login': // Redirect an authenticated user to the profile page. $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()])); break; case 'user.register': // Redirect an authenticated user to the profile form. $event->setResponse($this->redirect('entity.user.edit_form', ['user' => $this->account->id()])); break; } } elseif ($route_name === 'user.page') { $event->setResponse($this->redirect('user.login')); } } }
/** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $route_match = RouteMatch::createFromRequest($event->getRequest()); if ($this->maintenanceMode->applies($route_match)) { // Don't cache maintenance mode pages. \Drupal::service('page_cache_kill_switch')->trigger(); if (!$this->maintenanceMode->exempt($this->account)) { // Deliver the 503 page if the site is in maintenance mode and the // logged in user is not allowed to bypass it. drupal_maintenance_theme(); $content = Xss::filterAdmin(SafeMarkup::format($this->config->get('system.maintenance')->get('message'), array('@site' => $this->config->get('system.site')->get('name')))); $output = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $content], $this->t('Site under maintenance'), 'maintenance_page'); $response = new Response($output, 503); $event->setResponse($response); } else { // Display a message if the logged in user has access to the site in // maintenance mode. However, suppress it on the maintenance mode // settings page. if ($route_match->getRouteName() != 'system.site_maintenance_mode') { if ($this->account->hasPermission('administer site configuration')) { $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE); } else { $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE); } } } } }
/** * Tests handle with a non existing view. * * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function testHandleWithNotExistingView() { // Pass in a non existent view. $random_view_id = $this->randomMachineName(); $request = new Request(); $request->attributes->set('view_id', $random_view_id); $request->attributes->set('display_id', 'default'); $route_match = RouteMatch::createFromRequest($request); $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $request, $route_match); }
/** * A custom access check. * * @param \Drupal\Core\Session\AccountInterface $account * Run access checks for this account. * @param \Drupal\Core\Routing\RouteMatch $routeMatch * Run access checks against the account provided by this router match. * * @return \Drupal\Core\Access\AccessResult * Access is allowed if the id of the two accounts are the same. */ public function access(AccountInterface $account, RouteMatch $routeMatch) { $access = AccessResult::allowedIf($routeMatch && $routeMatch->getRawParameter('user') == $account->id()); $access->addCacheContexts(['user']); return $access; }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $links = array(); // General path-based breadcrumbs. Use the actual request path, prior to // resolving path aliases, so the breadcrumb can be defined by simply // creating a hierarchy of path aliases. $path = trim($this->context->getPathInfo(), '/'); $path_elements = explode('/', $path); $exclude = array(); // Don't show a link to the front-page path. $front = $this->config->get('page.front'); $exclude[$front] = TRUE; // /user is just a redirect, so skip it. // @todo Find a better way to deal with /user. $exclude['user'] = TRUE; while (count($path_elements) > 1) { array_pop($path_elements); // Copy the path elements for up-casting. $route_request = $this->getRequestForPath(implode('/', $path_elements), $exclude); if ($route_request) { $route_match = RouteMatch::createFromRequest($route_request); $access = $this->accessManager->check($route_match, $this->currentUser); if ($access) { $title = $this->titleResolver->getTitle($route_request, $route_match->getRouteObject()); } if ($access) { if (!isset($title)) { // Fallback to using the raw path component as the title if the // route is missing a _title or _title_callback attribute. $title = str_replace(array('-', '_'), ' ', Unicode::ucfirst(end($path_elements))); } $url = Url::fromRouteMatch($route_match); $links[] = new Link($title, $url); } } } if ($path && $path != $front) { // Add the Home link, except for the front page. $links[] = Link::createFromRoute($this->t('Home'), '<front>'); } return array_reverse($links); }
/** * @covers ::determineActiveTheme */ public function testDetermineActiveThemeDefaultTheme() { $theme = 'bartik'; // When the theme is the system default, an empty string is provided as the // theme token. See system_js_settings_alter(). $theme_token = ''; $request = new Request([], ['ajax_page_state' => ['theme' => $theme, 'theme_token' => $theme_token]]); $this->requestStack->push($request); $route_match = RouteMatch::createFromRequest($request); $this->tokenGenerator->validate(Argument::cetera())->shouldNotBeCalled(); $result = $this->negotiator->determineActiveTheme($route_match); $this->assertSame($theme, $result); }
/** * Tests the page controller with arguments of a overridden page view. * * This test care about upcasted values and ensures that the raw variables * are pulled in. */ public function testHandleWithArgumentsOnOverriddenRouteWithUpcasting() { $request = new Request(); $request->attributes->set('view_id', 'test_page_view'); $request->attributes->set('display_id', 'page_1'); // Add the argument to the request. $request->attributes->set('test_entity', $this->getMock('Drupal\\Core\\Entity\\EntityInterface')); $raw_variables = new ParameterBag(array('test_entity' => 'example_id')); $request->attributes->set('_raw_variables', $raw_variables); $options = ['_view_argument_map' => ['arg_0' => 'test_entity'], '_view_display_plugin_class' => '\\Drupal\\views\\Plugin\\views\\display\\Page']; $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test/{test_entity}', ['view_id' => 'test_page_view', 'display_id' => 'default'], [], $options)); $route_match = RouteMatch::createFromRequest($request); $result = $this->pageController->handle($route_match->getParameter('view_id'), $route_match->getParameter('display_id'), $route_match); $build = ['#type' => 'view', '#name' => 'test_page_view', '#display_id' => 'page_1', '#embed' => FALSE, '#arguments' => ['example_id'], '#cache' => ['keys' => ['view', 'test_page_view', 'display', 'page_1', 'args', 'example_id']]] + $this->defaultRenderArray; $this->assertEquals($build, $result); }
/** * {@inheritdoc} */ public function checkRequest(Request $request, AccountInterface $account = NULL, $return_as_object = FALSE) { $route_match = RouteMatch::createFromRequest($request); return $this->check($route_match, $account, $request, $return_as_object); }
/** * Tests getArguments with a route match and a PSR-7 request. * * @covers ::getArguments * @covers ::doGetArguments */ public function testGetArgumentsWithRouteMatchAndPsr7Request() { $request = Request::create('/test'); $mock_controller = new MockControllerPsr7(); $arguments = $this->controllerResolver->getArguments($request, [$mock_controller, 'getControllerWithRequestAndRouteMatch']); $this->assertEquals(RouteMatch::createFromRequest($request), $arguments[0], 'Ensure that the route match object is passed along as well'); $this->assertInstanceOf('Psr\\Http\\Message\\ServerRequestInterface', $arguments[1], 'Ensure that the PSR-7 object is passed along as well'); }
/** * {@inheritdoc} */ protected function doGetArguments(Request $request, $controller, array $parameters) { $attributes = $request->attributes->all(); $arguments = array(); foreach ($parameters as $param) { if (array_key_exists($param->name, $attributes)) { $arguments[] = $attributes[$param->name]; } elseif ($param->getClass() && $param->getClass()->isInstance($request)) { $arguments[] = $request; } elseif ($param->getClass() && ($param->getClass()->name == 'Drupal\\Core\\Routing\\RouteMatchInterface' || is_subclass_of($param->getClass()->name, 'Drupal\\Core\\Routing\\RouteMatchInterface'))) { $arguments[] = RouteMatch::createFromRequest($request); } elseif ($param->isDefaultValueAvailable()) { $arguments[] = $param->getDefaultValue(); } else { if (is_array($controller)) { $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]); } elseif (is_object($controller)) { $repr = get_class($controller); } else { $repr = $controller; } throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name)); } } // The parameter converter overrides the raw request attributes with the // upcasted objects. However, it keeps a backup copy of the original, raw // values in a special request attribute ('_raw_variables'). If a controller // argument has a type hint, we pass it the upcasted object, otherwise we // pass it the original, raw value. if ($request->attributes->has('_raw_variables') && ($raw = $request->attributes->get('_raw_variables')->all())) { foreach ($parameters as $parameter) { // Use the raw value if a parameter has no typehint. if (!$parameter->getClass() && isset($raw[$parameter->name])) { $position = $parameter->getPosition(); $arguments[$position] = $raw[$parameter->name]; } } } return $arguments; }
public function resetViewCount(Request $request) { \Drupal::state()->delete('mollom_test.view_count'); $route_match = $route = RouteMatch::createFromRequest($request); return $this->redirect($route_match->getRouteName(), $route_match->getRawParameters()->all()); }
/** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); if ($this->maintenanceMode->applies($route_match)) { // Don't cache maintenance mode pages. \Drupal::service('page_cache_kill_switch')->trigger(); if (!$this->maintenanceMode->exempt($this->account)) { // Deliver the 503 page if the site is in maintenance mode and the // logged in user is not allowed to bypass it. // If the request format is not 'html' then show default maintenance // mode page else show a text/plain page with maintenance message. if ($request->getRequestFormat() !== 'html') { $response = new Response($this->getSiteMaintenanceMessage(), 503, array('Content-Type' => 'text/plain')); $event->setResponse($response); return; } drupal_maintenance_theme(); $response = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page'); $response->setStatusCode(503); $event->setResponse($response); } else { // Display a message if the logged in user has access to the site in // maintenance mode. However, suppress it on the maintenance mode // settings page. if ($route_match->getRouteName() != 'system.site_maintenance_mode') { if ($this->account->hasPermission('administer site configuration')) { $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href=":url">Go online.</a>', array(':url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE); } else { $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE); } } } } }
/** * Default implementation of the provider filter. * * Checks whether a provider is allowed as per the _auth option on a route. If * the option is not set or if the request did not match any route, only * providers from the global provider set are allowed. * * If no filter is registered for the given provider id, the default filter * is applied. * * @param \Symfony\Component\HttpFoundation\Request $request * The incoming request. * @param string $provider_id * The id of the authentication provider to check access for. * * @return bool * TRUE if provider is allowed, FALSE otherwise. */ protected function defaultFilter(Request $request, $provider_id) { $route = RouteMatch::createFromRequest($request)->getRouteObject(); $has_auth_option = isset($route) && $route->hasOption('_auth'); if ($has_auth_option) { return in_array($provider_id, $route->getOption('_auth')); } else { return isset($this->globalProviders[$provider_id]); } }
/** * {@inheritdoc} */ protected function doGetArguments(Request $request, $controller, array $parameters) { $attributes = $request->attributes->all(); $raw_parameters = $request->attributes->has('_raw_variables') ? $request->attributes->get('_raw_variables') : []; $arguments = array(); foreach ($parameters as $param) { if (array_key_exists($param->name, $attributes)) { $arguments[] = $attributes[$param->name]; } elseif (array_key_exists($param->name, $raw_parameters)) { $arguments[] = $attributes[$param->name]; } elseif ($param->getClass() && $param->getClass()->isInstance($request)) { $arguments[] = $request; } elseif ($param->getClass() && $param->getClass()->name === ServerRequestInterface::class) { $arguments[] = $this->httpMessageFactory->createRequest($request); } elseif ($param->getClass() && ($param->getClass()->name == RouteMatchInterface::class || is_subclass_of($param->getClass()->name, RouteMatchInterface::class))) { $arguments[] = RouteMatch::createFromRequest($request); } elseif ($param->isDefaultValueAvailable()) { $arguments[] = $param->getDefaultValue(); } else { if (is_array($controller)) { $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]); } elseif (is_object($controller)) { $repr = get_class($controller); } else { $repr = $controller; } throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->name)); } } return $arguments; }
/** * Asserts that caching is denied on the private image style download route. * * @dataProvider providerPrivateImageStyleDownloadPolicy * @covers ::check */ public function testPrivateImageStyleDownloadPolicy($expected_result, $route_name) { $this->routeMatch->expects($this->once())->method('getRouteName')->will($this->returnValue($route_name)); $actual_result = $this->policy->check($this->response, $this->request); $this->assertSame($expected_result, $actual_result); }
/** * Tests getArguments with a route match and a request. * * @covers ::getArguments * @covers ::doGetArguments */ public function testGetArgumentsWithRouteMatchAndRequest() { $request = Request::create('/test'); $mock_controller = new MockController(); $arguments = $this->controllerResolver->getArguments($request, [$mock_controller, 'getControllerWithRequestAndRouteMatch']); $this->assertEquals([RouteMatch::createFromRequest($request), $request], $arguments); }
/** * Returns the route match for a passed in request. * * @param \Symfony\Component\HttpFoundation\Request $request * A request object. * * @return \Drupal\Core\Routing\RouteMatchInterface * A route match object created from the request. */ protected function getRouteMatch(Request $request) { if (isset($this->routeMatches[$request])) { $route_match = $this->routeMatches[$request]; } else { $route_match = RouteMatch::createFromRequest($request); // Since getRouteMatch() might be invoked both before and after routing // is completed, only statically cache the route match after there's a // matched route. if ($route_match->getRouteObject()) { $this->routeMatches[$request] = $route_match; } } return $route_match; }
/** * Language translations overview page for a configuration name. * * @param \Symfony\Component\HttpFoundation\Request $request * Page request object. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match. * @param string $plugin_id * The plugin ID of the mapper. * * @return array * Page render array. */ public function itemPage(Request $request, RouteMatchInterface $route_match, $plugin_id) { /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */ $mapper = $this->configMapperManager->createInstance($plugin_id); $mapper->populateFromRouteMatch($route_match); $page = array(); $page['#title'] = $this->t('Translations for %label', array('%label' => $mapper->getTitle())); $languages = $this->languageManager->getLanguages(); if (count($languages) == 1) { drupal_set_message($this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', array(':url' => $this->url('entity.configurable_language.collection'))), 'warning'); } $original_langcode = $mapper->getLangcode(); if (!isset($languages[$original_langcode])) { // If the language is not configured on the site, create a dummy language // object for this listing only to ensure the user gets useful info. $language_name = $this->languageManager->getLanguageName($original_langcode); $languages[$original_langcode] = new Language(array('id' => $original_langcode, 'name' => $language_name)); } // We create a fake request object to pass into // ConfigMapperInterface::populateFromRouteMatch() for the different languages. // Creating a separate request for each language and route is neither easily // possible nor performant. $fake_request = $request->duplicate(); $page['languages'] = array('#type' => 'table', '#header' => array($this->t('Language'), $this->t('Operations'))); foreach ($languages as $language) { $langcode = $language->getId(); // This is needed because // ConfigMapperInterface::getAddRouteParameters(), for example, // needs to return the correct language code for each table row. $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)', array('@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 = array(); if ($edit_access) { $operations['edit'] = array('title' => $this->t('Edit'), 'url' => Url::fromRoute($mapper->getBaseRouteName(), $mapper->getBaseRouteParameters(), ['query' => ['destination' => $mapper->getOverviewPath()]])); } } else { $language_name = $language->getName(); $operations = array(); // If no translation exists for this language, link to add one. if (!$mapper->hasTranslation($language)) { $operations['add'] = array('title' => $this->t('Add'), 'url' => Url::fromRoute($mapper->getAddRouteName(), $mapper->getAddRouteParameters())); } else { // Otherwise, link to edit the existing translation. $operations['edit'] = array('title' => $this->t('Edit'), 'url' => Url::fromRoute($mapper->getEditRouteName(), $mapper->getEditRouteParameters())); $operations['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute($mapper->getDeleteRouteName(), $mapper->getDeleteRouteParameters())); } } $page['languages'][$langcode]['language'] = array('#markup' => $language_name); $page['languages'][$langcode]['operations'] = array('#type' => 'operations', '#links' => $operations); } return $page; }