getRouteCollection example

public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->resourceConfigStorage = $entity_type_manager->getStorage('rest_resource_config');
  }

  /** * Provides routes on route rebuild time. * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The route build event. */
  public function onDynamicRouteEvent(RouteBuildEvent $event) {
    $route_collection = $event->getRouteCollection();

    $resource_configs = $this->resourceConfigStorage->loadMultiple();
    // Iterate over all REST resource config entities.     foreach ($resource_configs as $resource_config) {
      // We only care about REST resource config entities for the       // \Drupal\rest\Plugin\rest\resource\EntityResource plugin.       $plugin_id = $resource_config->toArray()['plugin_id'];
      if (substr($plugin_id, 0, 6) !== 'entity') {
        continue;
      }

      

    }

    /** * @throws InvalidArgumentException When route does not exist */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input$output);
        $name = $input->getArgument('name');
        $helper = new DescriptorHelper($this->fileLinkFormatter);
        $routes = $this->router->getRouteCollection();
        $container = null;
        if ($this->fileLinkFormatter) {
            $container = fn () => $this->getContainerBuilder($this->getApplication()->getKernel());
        }

        if ($name) {
            $route = $routes->get($name);
            $matchingRoutes = $this->findRouteNameContaining($name$routes);

            if (!$input->isInteractive() && !$route && \count($matchingRoutes) > 1) {
                $helper->describe($io$this->findRouteContaining($name$routes)[
                    
/** * @var ExpressionFunctionProviderInterface[] */
    private iterable $expressionLanguageProviders;

    public function __construct(Profiler $profiler = null, Environment $twig, UrlMatcherInterface $matcher = null, RouteCollection $routes = null, iterable $expressionLanguageProviders = [])
    {
        $this->profiler = $profiler;
        $this->twig = $twig;
        $this->matcher = $matcher;
        $this->routes = (null === $routes && $matcher instanceof RouterInterface) ? $matcher->getRouteCollection() : $routes;
        $this->expressionLanguageProviders = $expressionLanguageProviders;
    }

    /** * Renders the profiler panel for the given token. * * @throws NotFoundHttpException */
    public function panelAction(string $token): Response
    {
        if (null === $this->profiler) {
            
$container->get('router')
    );
  }

  /** * {@inheritdoc} */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];

    // Add the moderated content task if the route exists.     if ($this->router->getRouteCollection()->get('content_moderation.admin_moderated_content') !== NULL) {
      $this->derivatives['content_moderation.moderated_content'] = [
        'route_name' => 'content_moderation.admin_moderated_content',
        'title' => $this->t('Moderated content'),
        'parent_id' => 'system.admin_content',
        'weight' => 1,
      ];
    }

    // Add the latest version tab to entities.     $latest_version_entities = array_filter($this->entityTypeManager->getDefinitions()function DEntityTypeInterface $type) {
      return $this->moderationInfo->canModerateEntitiesOfEntityType($type) && $type->hasLinkTemplate('latest-version');
    });
public function __construct(SectionStorageManagerInterface $section_storage_manager) {
    $this->sectionStorageManager = $section_storage_manager;
  }

  /** * Alters existing routes for a specific collection. * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The route build event. */
  public function onAlterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();
    foreach ($this->sectionStorageManager->getDefinitions() as $plugin_id => $definition) {
      $this->sectionStorageManager->loadEmpty($plugin_id)->buildRoutes($collection);
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    // Run after \Drupal\field_ui\Routing\RouteSubscriber.     $events[RoutingEvents::ALTER] = ['onAlterRoutes', -110];
    


    public function testBuildKernel(): void
    {
        $kernel = new Kernel('test', true);
        $kernel->boot();

        static::assertTrue($kernel->getContainer()->has('router'));

        /** @var Router $router */
        $router = $kernel->getContainer()->get('router');
        static::assertCount(12, $router->getRouteCollection());
    }
}

  public function onRoutingAlterAddFormats(RouteBuildEvent $event) {
    $route_names = [
      'user.login_status.http',
      'user.login.http',
      'user.logout.http',
      'user.pass.http',
    ];
    $routes = $event->getRouteCollection();
    foreach ($route_names as $route_name) {
      if ($route = $routes->get($route_name)) {
        $formats = explode('|', $route->getRequirement('_format'));
        $formats = array_unique(array_merge($formats$this->serializerFormats));
        $route->setRequirement('_format', implode('|', $formats));
      }
    }
  }

}
public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /** * Collects all path roots. * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The route build event. */
  public function onRouteAlter(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();
    foreach ($collection->all() as $route) {
      $bits = explode('/', ltrim($route->getPath(), '/'));
      $this->pathRoots[$bits[0]] = $bits[0];
    }
  }

  /** * {@inheritdoc} */
  public function onRouteFinished() {
    $this->state->set('router.path_roots', array_keys($this->pathRoots));
    

    }
  }

  /** * Delegates the route altering to self::alterRoutes(). * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The route build event. */
  public function onAlterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();
    $this->alterRoutes($collection);
  }

}

  public function onDynamicRouteEvent(RouteBuildEvent $event) {
    // Iterate over all enabled REST resource config entities.     /** @var \Drupal\rest\RestResourceConfigInterface[] $resource_configs */
    $resource_configs = $this->resourceConfigStorage->loadMultiple();
    foreach ($resource_configs as $resource_config) {
      if ($resource_config->status()) {
        $resource_routes = $this->getRoutesForResourceConfig($resource_config);
        $event->getRouteCollection()->addCollection($resource_routes);
      }
    }
  }

  /** * Provides all routes for a given REST resource config. * * This method determines where a resource is reachable, what path * replacements are used, the required HTTP method for the operation etc. * * @param \Drupal\rest\RestResourceConfigInterface $rest_resource_config * The rest resource config. * * @return \Symfony\Component\Routing\RouteCollection * The route collection. */

  protected function checkRevisionViewAccess(EntityInterface $entity, AccountInterface $account) {
    assert($entity instanceof RevisionableInterface);
    assert(!$entity->isDefaultRevision(), 'It is not necessary to check revision access when the entity is the default revision.');
    $entity_type = $entity->getEntityType();
    $access = $entity->access('view all revisions', $account, TRUE);
    // Apply content_moderation's additional access logic.     // @see \Drupal\content_moderation\Access\LatestRevisionCheck::access()     if ($entity_type->getLinkTemplate('latest-version') && $entity->isLatestRevision() && isset($this->latestRevisionCheck)) {
      // The latest revision access checker only expects to be invoked by the       // routing system, which makes it necessary to fake a route match.       $routes = $this->router->getRouteCollection();
      $resource_type = $this->resourceTypeRepository->get($entity->getEntityTypeId()$entity->bundle());
      $route_name = sprintf('jsonapi.%s.individual', $resource_type->getTypeName());
      $route = $routes->get($route_name);
      $route->setOption('_content_moderation_entity_type', 'entity');
      $route_match = new RouteMatch($route_name$route['entity' => $entity]['entity' => $entity->uuid()]);
      $moderation_access_result = $this->latestRevisionCheck->access($route$route_match$account);
      $access = $access->andIf($moderation_access_result);
    }
    return $access;
  }

}
$no_big_pipe_routes = [
      // The batch system uses a <meta> refresh to work without JavaScript.       'system.batch_page.html',
      // When a user would install the BigPipe module using a browser and with       // JavaScript disabled, the first response contains the status messages       // for installing a module, but then the BigPipe no-JS redirect occurs,       // which then causes the user to not see those status messages.       // @see https://www.drupal.org/node/2469431#comment-10901944       'system.modules_list',
    ];

    $route_collection = $event->getRouteCollection();
    foreach ($no_big_pipe_routes as $excluded_route) {
      if ($route = $route_collection->get($excluded_route)) {
        $route->setOption('_no_big_pipe', TRUE);
      }
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    
public function __construct(EntityResolverManager $entity_resolver_manager) {
    $this->resolverManager = $entity_resolver_manager;
  }

  /** * Applies parameter converters to route parameters. * * @param \Drupal\Core\Routing\RouteBuildEvent $event * The event to process. */
  public function onRoutingRouteAlterSetType(RouteBuildEvent $event) {
    foreach ($event->getRouteCollection() as $route) {
      $this->resolverManager->setRouteOptions($route);
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[RoutingEvents::ALTER][] = ['onRoutingRouteAlterSetType', -150];
    return $events;
  }

}
$sc = $this->getPsr11ServiceContainer($routes);
        $parameters = $this->getParameterBag([
            'locale' => 'es',
            'foo' => 'bar',
        ]);

        $router = new Router($sc, 'foo', [], null, $parameters);

        $this->assertSame('/en', $router->generate('foo', ['_locale' => 'en']));
        $this->assertSame('/', $router->generate('foo', ['_locale' => 'es']));
        $this->assertSame('"bar" == "bar"', $router->getRouteCollection()->get('foo')->getCondition());
    }

    public function testGenerateWithServiceParamWithSfContainer()
    {
        $routes = new RouteCollection();

        $routes->add('foo', new Route(
            ' /{_locale}',
            [
                '_locale' => '%locale%',
            ],
            [
/** * Gets the UrlMatcher or RequestMatcher instance associated with this Router. */
    public function getMatcher(): UrlMatcherInterface|RequestMatcherInterface
    {
        if (null !== $this->matcher) {
            return $this->matcher;
        }

        if (null === $this->options['cache_dir']) {
            $routes = $this->getRouteCollection();
            $compiled = is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true);
            if ($compiled) {
                $routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
            }
            $this->matcher = new $this->options['matcher_class']($routes$this->context);
            if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
                foreach ($this->expressionLanguageProviders as $provider) {
                    $this->matcher->addExpressionLanguageProvider($provider);
                }
            }

            
Home | Imprint | This part of the site doesn't use cookies.