Version 1
[yaffs-website] / web / core / lib / Drupal / Core / EventSubscriber / PathRootsSubscriber.php
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
5 use Drupal\Core\State\StateInterface;
6 use Drupal\Core\Routing\RouteBuildEvent;
7 use Drupal\Core\Routing\RoutingEvents;
8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
10 /**
11  * Provides all available first bits of all route paths.
12  */
13 class PathRootsSubscriber implements EventSubscriberInterface {
14
15   /**
16    * Stores the path roots available in the router.
17    *
18    * A path root is the first virtual directory of a path, like 'admin', 'node'
19    * or 'user'.
20    *
21    * @var array
22    */
23   protected $pathRoots = [];
24
25   /**
26    * The state key value store.
27    *
28    * @var \Drupal\Core\State\StateInterface
29    */
30   protected $state;
31
32   /**
33    * Constructs a new PathRootsSubscriber instance.
34    *
35    * @param \Drupal\Core\State\StateInterface $state
36    *   The state key value store.
37    */
38   public function __construct(StateInterface $state) {
39     $this->state = $state;
40   }
41
42   /**
43    * Collects all path roots.
44    *
45    * @param \Drupal\Core\Routing\RouteBuildEvent $event
46    *   The route build event.
47    */
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];
53     }
54   }
55
56   /**
57    * {@inheritdoc}
58    */
59   public function onRouteFinished() {
60     $this->state->set('router.path_roots', array_keys($this->pathRoots));
61     $this->pathRoots = [];
62   }
63
64   /**
65    * {@inheritdoc}
66    */
67   public static function getSubscribedEvents() {
68     $events = [];
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'];
72     return $events;
73   }
74
75 }