routeProvider = $route_provider; $this->state = $state; $this->cache = $cache; } /** * 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); } } } /** * 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 ($collection->all() as $name => $route) { if (strpos($route->getPath(), '/admin/') !== 0 && $route->getPath() != '/admin') { $this->nonAdminRoutesOnRebuild[] = $name; } } $this->nonAdminRoutesOnRebuild = array_unique($this->nonAdminRoutesOnRebuild); } /** * Store the non admin routes in state when the route building is finished. * * @param \Symfony\Component\EventDispatcher\Event $event * The route finish event. */ public function onFinishedRoutes(Event $event) { $this->state->set('routing.non_admin_routes', $this->nonAdminRoutesOnRebuild); $this->nonAdminRoutesOnRebuild = []; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { // Set a really low priority to catch as many as possible routes. $events[RoutingEvents::ALTER] = ['onAlterRoutes', -1024]; $events[RoutingEvents::FINISHED] = ['onFinishedRoutes']; // Load the routes before the controller is executed (which happens after // the kernel request event). $events[KernelEvents::REQUEST][] = ['onRequest']; return $events; } }