3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\State\StateInterface;
6 use Drupal\Core\Routing\RouteBuildEvent;
7 use Drupal\Core\Routing\RoutingEvents;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
11 * Provides all available first bits of all route paths.
13 class PathRootsSubscriber implements EventSubscriberInterface {
16 * Stores the path roots available in the router.
18 * A path root is the first virtual directory of a path, like 'admin', 'node'
23 protected $pathRoots = [];
26 * The state key value store.
28 * @var \Drupal\Core\State\StateInterface
33 * Constructs a new PathRootsSubscriber instance.
35 * @param \Drupal\Core\State\StateInterface $state
36 * The state key value store.
38 public function __construct(StateInterface $state) {
39 $this->state = $state;
43 * Collects all path roots.
45 * @param \Drupal\Core\Routing\RouteBuildEvent $event
46 * The route build event.
48 public function onRouteAlter(RouteBuildEvent $event) {
49 $collection = $event->getRouteCollection();
50 foreach ($collection->all() as $route) {
51 $bits = explode('/', ltrim($route->getPath(), '/'));
52 $this->pathRoots[$bits[0]] = $bits[0];
59 public function onRouteFinished() {
60 $this->state->set('router.path_roots', array_keys($this->pathRoots));
61 $this->pathRoots = [];
67 public static function getSubscribedEvents() {
69 // Try to set a low priority to ensure that all routes are already added.
70 $events[RoutingEvents::ALTER][] = ['onRouteAlter', -1024];
71 $events[RoutingEvents::FINISHED][] = ['onRouteFinished'];