RouteCollection example

// PSR-4 directory loader has no env-aware logic, so we drop the $env constructor parameter.         parent::__construct();
    }

    /** * @param array{path: string, namespace: string} $resource */
    public function load(mixed $resource, string $type = null): ?RouteCollection
    {
        $path = $this->locator->locate($resource['path']$this->currentDirectory);
        if (!is_dir($path)) {
            return new RouteCollection();
        }

        return $this->loadFromDirectory($pathtrim($resource['namespace'], '\\'));
    }

    public function supports(mixed $resource, string $type = null): bool
    {
        return ('attribute' === $type || 'annotation' === $type) && \is_array($resource) && isset($resource['path']$resource['namespace']);
    }

    public function forDirectory(string $currentDirectory)static
    {
$converter = $this->createMock('Drupal\Core\ParamConverter\ParamConverterInterface');
    $converter->expects($this->any())
      ->method('applies')
      ->with($this->anything(), 'id', $this->anything())
      ->willReturn(TRUE);
    $this->manager->addConverter($converter, 'applied');

    $route = new Route($path);
    if ($parameters) {
      $route->setOption('parameters', $parameters);
    }
    $collection = new RouteCollection();
    $collection->add('test_route', $route);

    $this->manager->setRouteParameterConverters($collection);
    foreach ($collection as $route) {
      $result = $route->getOption('parameters');
      if ($expected) {
        $this->assertSame($expected$result['id']['converter']);
      }
      else {
        $this->assertNull($result);
      }
    }
'_field_ui_view_mode_access' => 'administer with_bundle_parameter display',
          '_layout_builder_access' => 'view',
        ],
        [
          'parameters' => [
            'section_storage' => ['layout_builder_tempstore' => TRUE],
          ],
        ]
      ),
    ];

    $collection = new RouteCollection();
    $collection->add('known', new Route('/admin/entity/whatever', [][]['_admin_route' => TRUE]));
    $collection->add('with_bundle', new Route('/admin/entity/{bundle}'));

    $this->plugin->buildRoutes($collection);
    $this->assertEquals($expected$collection->all());
    $this->assertSame(array_keys($expected)array_keys($collection->all()));
  }

  /** * @covers ::buildRoutes */
  
use Traits\RouteTrait;

    private RouteCollection $parent;
    private ?CollectionConfigurator $parentConfigurator;
    private ?array $parentPrefixes;
    private string|array|null $host = null;

    public function __construct(RouteCollection $parent, string $name, self $parentConfigurator = null, array $parentPrefixes = null)
    {
        $this->parent = $parent;
        $this->name = $name;
        $this->collection = new RouteCollection();
        $this->route = new Route('');
        $this->parentConfigurator = $parentConfigurator; // for GC control         $this->parentPrefixes = $parentPrefixes;
    }

    public function __sleep(): array
    {
        throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
    }

    public function __wakeup()
    {
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Routing\RouteCollection;

class DirectoryLoader extends FileLoader
{
    public function load(mixed $file, string $type = null): mixed
    {
        $path = $this->locator->locate($file);

        $collection = new RouteCollection();
        $collection->addResource(new DirectoryResource($path));

        foreach (scandir($path) as $dir) {
            if ('.' !== $dir[0]) {
                $this->setCurrentDir($path);
                $subPath = $path.'/'.$dir;
                $subType = null;

                if (is_dir($subPath)) {
                    $subPath .= '/';
                    $subType = 'directory';
                }
use Symfony\Component\Routing\RouteCollection;

/** * Provides routes for nodes. */
class NodeRouteProvider implements EntityRouteProviderInterface {

  /** * {@inheritdoc} */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $route_collection = new RouteCollection();
    $route = (new Route('/node/{node}'))
      ->addDefaults([
        '_controller' => '\Drupal\node\Controller\NodeViewController::view',
        '_title_callback' => '\Drupal\node\Controller\NodeViewController::title',
      ])
      ->setRequirement('node', '\d+')
      ->setRequirement('_entity_access', 'node.view');
    $route_collection->add('entity.node.canonical', $route);

    $route = (new Route('/node/{node}/delete'))
      ->addDefaults([
        
foreach ($this->getRoutes()->all() as $name => $route) {
            if ($host = $route->getHost()) {
                $matchHost = true;
                $host = '/'.strtr(strrev($host), '}.{', '(/)');
            }

            $routes->addRoute($host ?: '/(.*)', [$name$route]);
        }

        if ($matchHost) {
            $compiledRoutes = [true];
            $routes = $routes->populateCollection(new RouteCollection());
        } else {
            $compiledRoutes = [false];
            $routes = $this->getRoutes();
        }

        [$staticRoutes$dynamicRoutes] = $this->groupStaticRoutes($routes);

        $conditions = [null];
        $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes$conditions);
        $chunkLimit = \count($dynamicRoutes);

        
$account = User::create([
      'name' => $this->randomMachineName(),
      'status' => 1,
    ]);
    $account->save();
    $this->container->get('current_user')->setAccount($account);

    $this->menuLinkManager = $this->container->get('plugin.manager.menu.link');
    $this->linkTree = $this->container->get('menu.link_tree');
    $this->blockManager = $this->container->get('plugin.manager.block');

    $routes = new RouteCollection();
    $requirements = ['_access' => 'TRUE'];
    $options = ['_access_checks' => ['access_check.default']];
    $routes->add('example1', new Route('/example1', []$requirements$options));
    $routes->add('example2', new Route('/example2', []$requirements$options));
    $routes->add('example3', new Route('/example3', []$requirements$options));
    $routes->add('example4', new Route('/example4', []$requirements$options));
    $routes->add('example5', new Route('/example5', []$requirements$options));
    $routes->add('example6', new Route('/example6', []$requirements$options));
    $routes->add('example7', new Route('/example7', []$requirements$options));
    $routes->add('example8', new Route('/example8', []$requirements$options));

    
throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
        }

        $this->yamlParser ??= new YamlParser();

        try {
            $parsedConfig = $this->yamlParser->parseFile($path, Yaml::PARSE_CONSTANT);
        } catch (ParseException $e) {
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $path).$e->getMessage(), 0, $e);
        }

        $collection = new RouteCollection();
        $collection->addResource(new FileResource($path));

        // empty file         if (null === $parsedConfig) {
            return $collection;
        }

        // not an array         if (!\is_array($parsedConfig)) {
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
        }

        
use Traits\RouteTrait;

    private RouteCollection $parent;
    private ?CollectionConfigurator $parentConfigurator;
    private ?array $parentPrefixes;
    private string|array|null $host = null;

    public function __construct(RouteCollection $parent, string $name, self $parentConfigurator = null, array $parentPrefixes = null)
    {
        $this->parent = $parent;
        $this->name = $name;
        $this->collection = new RouteCollection();
        $this->route = new Route('');
        $this->parentConfigurator = $parentConfigurator; // for GC control         $this->parentPrefixes = $parentPrefixes;
    }

    public function __sleep(): array
    {
        throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
    }

    /** * @return void */
<?php
$path = '/1/2/3';

return new \Symfony\Component\Routing\RouteCollection();


    /** * Loads from annotations from a file. * * @throws \InvalidArgumentException When the file does not exist or its routes cannot be parsed */
    public function load(mixed $file, string $type = null): ?RouteCollection
    {
        $path = $this->locator->locate($file);

        $collection = new RouteCollection();
        if ($class = $this->findClass($path)) {
            $refl = new \ReflectionClass($class);
            if ($refl->isAbstract()) {
                return null;
            }

            $collection->addResource(new FileResource($path));
            $collection->addCollection($this->loader->load($class$type));
        }

        gc_mem_caches();

        

  protected function childRoutes(EntityTypeInterface $entity_type): array {
    $route_names = [];

    if ($field_ui_base_route = $entity_type->get('field_ui_base_route')) {
      $updated_routes = new RouteCollection();
      $updated_routes->add($field_ui_base_route$this->collection->get($field_ui_base_route));
      $event = new RouteBuildEvent($updated_routes);

      // Apply route subscribers that add routes based on field_ui_base_route,       // in the order of their weights.       $subscribers = [
        'field_ui' => 'field_ui.subscriber',
        'content_translation' => 'content_translation.subscriber',
      ];
      foreach ($subscribers as $module_name => $service_name) {
        if ($this->moduleHandler->moduleExists($module_name)) {
          
foreach ($this->getRoutes()->all() as $name => $route) {
            if ($host = $route->getHost()) {
                $matchHost = true;
                $host = '/'.strtr(strrev($host), '}.{', '(/)');
            }

            $routes->addRoute($host ?: '/(.*)', [$name$route]);
        }

        if ($matchHost) {
            $compiledRoutes = [true];
            $routes = $routes->populateCollection(new RouteCollection());
        } else {
            $compiledRoutes = [false];
            $routes = $this->getRoutes();
        }

        [$staticRoutes$dynamicRoutes] = $this->groupStaticRoutes($routes);

        $conditions = [null];
        $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes$conditions);
        $chunkLimit = \count($dynamicRoutes);

        

  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  /** * {@inheritdoc} */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $collection = new RouteCollection();

    $entity_type_id = $entity_type->id();

    if ($entity_permissions_route = $this->getEntityPermissionsRoute($entity_type)) {
      $collection->add("entity.$entity_type_id.entity_permissions_form", $entity_permissions_route);
    }

    return $collection;
  }

  /** * Gets the entity permissions route. * * Built only for entity types that are bundles of other entity types and * define the 'entity-permissions-form' link template. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type. * * @return \Symfony\Component\Routing\Route|null * The generated route, if available. */
Home | Imprint | This part of the site doesn't use cookies.