Route example

$this->executable->style_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\style\StylePluginBase')
      ->disableOriginalConstructor()
      ->getMock();
    $this->display = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
      ->disableOriginalConstructor()
      ->getMock();

    $route_provider = $this->createMock('Drupal\Core\Routing\RouteProviderInterface');
    $route_provider->expects($this->any())
      ->method('getRouteByName')
      ->with('test_route')
      ->willReturn(new Route('/test-path'));

    $this->urlGenerator = $this->createMock('Drupal\Core\Routing\UrlGeneratorInterface');
    $this->pathValidator = $this->createMock('Drupal\Core\Path\PathValidatorInterface');

    $this->requestStack = new RequestStack();
    $this->requestStack->push(new Request());

    $this->unroutedUrlAssembler = $this->createMock('Drupal\Core\Utility\UnroutedUrlAssemblerInterface');
    $this->linkGenerator = $this->createMock('Drupal\Core\Utility\LinkGeneratorInterface');

    $this->renderer = $this->createMock('Drupal\Core\Render\RendererInterface');

    
'_has_active_workspace' => 'TRUE'], FALSE, FALSE, ['workspace']],
      [['_has_active_workspace' => 'FALSE'], TRUE, FALSE, ['workspace']],
      [['_has_active_workspace' => 'FALSE'], FALSE, TRUE, ['workspace']],
    ];
  }

  /** * @covers ::access * @dataProvider providerTestAccess */
  public function testAccess($requirements$has_active_workspace$access, array $contexts = []) {
    $route = new Route('', []$requirements);

    $workspace_manager = $this->prophesize(WorkspaceManagerInterface::class);
    $workspace_manager->hasActiveWorkspace()->willReturn($has_active_workspace);
    $access_check = new ActiveWorkspaceCheck($workspace_manager->reveal());

    $access_result = AccessResult::allowedIf($access)->addCacheContexts($contexts);
    $this->assertEquals($access_result$access_check->access($route));
  }

}

class MethodFilterTest extends UnitTestCase {

  /** * @covers ::filter */
  public function testWithAllowedMethod() {
    $request = Request::create('/test', 'GET');
    $collection = new RouteCollection();
    $collection->add('test_route.get', new Route('/test', [][][], '', []['GET']));
    $collection_before = clone $collection;

    $method_filter = new MethodFilter();
    $result_collection = $method_filter->filter($collection$request);

    $this->assertEquals($collection_before$result_collection);
  }

  /** * @covers ::filter */
  
<?php
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

return function Dstring $format) {
    $expectedRoutes = new RouteCollection();
    $expectedRoutes->add('imported.en', $route = new Route('/en/example'));
    $route->setHost('www.example.com');
    $route->setRequirement('_locale', 'en');
    $route->setDefault('_locale', 'en');
    $route->setDefault('_canonical_route', 'imported');
    $route->setDefault('_controller', 'ImportedController::someAction');
    $expectedRoutes->add('imported.nl', $route = new Route('/nl/voorbeeld'));
    $route->setHost('www.example.nl');
    $route->setRequirement('_locale', 'nl');
    $route->setDefault('_locale', 'nl');
    $route->setDefault('_canonical_route', 'imported');
    $route->setDefault('_controller', 'ImportedController::someAction');
    
$prophecy->getPermissionGranularity()
      ->willReturn('entity_type');
    $entity_type = $prophecy->reveal();
    $prophecy = $this->prophesize(EntityTypeManagerInterface::class);
    $prophecy->getDefinition('entity_type')
      ->willReturn($entity_type);
    $entity_type_manager = $prophecy->reveal();

    $bundle_form = new EntityPermissionsForm($permission_handler$role_storage$module_handler$config_manager$entity_type_manager);

    // Mock the method parameters.     $route = new Route('some.path');
    $route_match = $this->prophesize(RouteMatchInterface::class)->reveal();
    $prophecy = $this->prophesize(EntityTypeInterface::class);
    $prophecy->getBundleOf()
      ->willReturn('entity_type');
    $bundle_type = $prophecy->reveal();
    $prophecy = $this->prophesize(EntityInterface::class);
    $prophecy->getEntityType()
      ->willReturn($bundle_type);
    $prophecy->getConfigDependencyName()
      ->willReturn('node.type.article');
    $bundle = $prophecy->reveal();

    
<?php
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

return static function Dstring $format) {
    $expectedRoutes = new RouteCollection();

    $expectedRoutes->add('route', new Route('/hello'));
    $expectedRoutes->addAlias('alias', 'route');
    $expectedRoutes->addAlias('deprecated', 'route')
        ->setDeprecated('foo/bar', '1.0.0', '');
    $expectedRoutes->addAlias('deprecated-with-custom-message', 'route')
        ->setDeprecated('foo/bar', '1.0.0', 'foo %alias_id%.');
    $expectedRoutes->addAlias('deep', 'alias');
    $expectedRoutes->addAlias('overrided', 'route');

    $expectedRoutes->addResource(new FileResource(__DIR__."/alias.$format"));
    if ('yaml' === $format) {
        $expectedRoutes->addResource(new FileResource(__DIR__."/override.$format"));
    }
parent::setUp();

    $this->installEntitySchema('user');
    $this->installEntitySchema('menu_link_content');
  }

  /** * Tests the rediscovering. */
  public function testRediscover() {
    \Drupal::state()->set('menu_link_content_dynamic_route.routes', [
      'route_name_1' => new Route('/example-path'),
    ]);
    \Drupal::service('router.builder')->rebuild();

    // Set up a custom menu link pointing to a specific path.     $parent = MenuLinkContent::create([
      'title' => '<script>alert("Welcome to the discovered jungle!")</script>',
      'link' => [['uri' => 'internal:/example-path']],
      'menu_name' => 'tools',
    ]);
    $parent->save();
    $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
    
$this->assertInstanceOf(Route::class$route);
    $this->assertEquals('test_id', $route->getDefault('view_id'));
    $this->assertEquals('page_1', $route->getDefault('display_id'));
    $this->assertEquals('Drupal\views\Routing\ViewPageController::getTitle', $route->getDefault('_title_callback'));
  }

  /** * Tests the alter route method. */
  public function testAlterRoute() {
    $collection = new RouteCollection();
    $collection->add('test_route', new Route('test_route', ['_controller' => 'Drupal\Tests\Core\Controller\TestController::content']));
    $route_2 = new Route('test_route/example', ['_controller' => 'Drupal\Tests\Core\Controller\TestController::content']);
    $collection->add('test_route_2', $route_2);

    [$view] = $this->setupViewExecutableAccessPlugin();

    $display = [];
    $display['display_plugin'] = 'page';
    $display['id'] = 'page_1';
    $display['display_options'] = [
      'path' => 'test_route',
    ];
    
$this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name$route);
                continue;
            }
            $regex = $compiledRoute->getRegex();

            $pos = strrpos($regex, '$');
            $hasTrailingSlash = '/' === $regex[$pos - 1];
            $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);

            if (!preg_match($regex$pathinfo$matches)) {
                // does it match without any requirements?                 $r = new Route($route->getPath()$route->getDefaults()[]$route->getOptions());
                $cr = $r->compile();
                if (!preg_match($cr->getRegex()$pathinfo)) {
                    $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name$route);

                    continue;
                }

                foreach ($route->getRequirements() as $n => $regex) {
                    $r = new Route($route->getPath()$route->getDefaults()[$n => $regex]$route->getOptions());
                    $cr = $r->compile();

                    
public function testLoadDefaultOptions()
    {
        $loaderResolver = $this->createMock(LoaderResolverInterface::class);

        $loader = $this->createMock(LoaderInterface::class);

        $loaderResolver->expects($this->once())
            ->method('resolve')
            ->willReturn($loader);

        $routeCollection = new RouteCollection();
        $routeCollection->add('foo', new Route('/', [][]['utf8' => false]));
        $routeCollection->add('bar', new Route('/', []['_locale' => 'de']['foo' => 123]));

        $loader->expects($this->once())
            ->method('load')
            ->willReturn($routeCollection);

        $delegatingLoader = new DelegatingLoader($loaderResolver['utf8' => true]['_locale' => 'fr|en']);

        $loadedRouteCollection = $delegatingLoader->load('foo');
        $this->assertCount(2, $loadedRouteCollection);

        
'host' => NULL,
          'schemes' => [],
          'methods' => [],
          'condition' => '',
        ];
        // Ensure routes default to using Drupal's route compiler instead of         // Symfony's.         $route_info['options'] += [
          'compiler_class' => RouteCompiler::class,
        ];

        $route = new Route($route_info['path']$route_info['defaults']$route_info['requirements']$route_info['options']$route_info['host']$route_info['schemes']$route_info['methods']$route_info['condition']);
        $collection->add($name$route);
      }
    }

    // DYNAMIC is supposed to be used to add new routes based upon all the     // static defined ones.     $this->dispatcher->dispatch(new RouteBuildEvent($collection), RoutingEvents::DYNAMIC);

    // ALTER is the final step to alter all the existing routes. We cannot stop     // people from adding new routes here, but we define two separate steps to     // make it clear.

  protected function getBaseRoute($canonical_path$method) {
    return new Route($canonical_path[
      '_controller' => 'Drupal\rest\RequestHandler::handle',
    ],
      $this->getBaseRouteRequirements($method),
      [],
      '',
      [],
      // The HTTP method is a requirement for this route.       [$method]
    );
  }

  
$this->assertFalse($json['theme_initialized']);
  }

  /** * Ensure page-front template suggestion is added when on front page. */
  public function testFrontPageThemeSuggestion() {
    // Set the current route to user.login because theme_get_suggestions() will     // query it to see if we are on the front page.     $request = Request::create('/user/login');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login'));
    \Drupal::requestStack()->push($request);
    $this->config('system.site')->set('page.front', '/user/login')->save();
    $suggestions = theme_get_suggestions(['user', 'login'], 'page');
    // Set it back to not annoy the batch runner.     \Drupal::requestStack()->pop();
    $this->assertContains('page__front', $suggestions, 'Front page template was suggested.');
  }

  /** * Tests theme can provide classes. */
  
/** * Gets the reset page route. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type. * * @return \Symfony\Component\Routing\Route|null * The generated route, if available. */
  protected function getResetPageRoute(EntityTypeInterface $entity_type) {
    $route = new Route('/admin/structure/taxonomy/manage/{taxonomy_vocabulary}/reset');
    $route->setDefault('_entity_form', 'taxonomy_vocabulary.reset');
    $route->setDefault('_title', 'Reset');
    $route->setRequirement('_entity_access', 'taxonomy_vocabulary.reset all weights');
    $route->setOption('_admin_route', TRUE);
    $route->setOption('parameters', [
      'taxonomy_vocabulary' => [
        'with_config_overrides' => TRUE,
      ],
    ]);

    return $route;
  }
public function testAlterRoutes(Route $route$is_admin) {
    $collection = new RouteCollection();
    $collection->add('the_route', $route);
    (new AdminRouteSubscriber())->onAlterRoutes(new RouteBuildEvent($collection));

    $this->assertSame($is_admin$route->getOption('_admin_route'));
  }

  public function providerTestAlterRoutes() {
    $data = [];
    $data['non-admin'] = [
      new Route('/foo'),
      NULL,
    ];
    $data['admin prefix'] = [
      new Route('/admin/foo'),
      TRUE,
    ];
    $data['admin only'] = [
      new Route('/admin'),
      TRUE,
    ];
    $data['admin in part of a word'] = [
      
Home | Imprint | This part of the site doesn't use cookies.