annotate core/lib/Drupal/Core/EventSubscriber/PathRootsSubscriber.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\EventSubscriber;
Chris@0 4
Chris@0 5 use Drupal\Core\State\StateInterface;
Chris@0 6 use Drupal\Core\Routing\RouteBuildEvent;
Chris@0 7 use Drupal\Core\Routing\RoutingEvents;
Chris@0 8 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
Chris@0 9
Chris@0 10 /**
Chris@0 11 * Provides all available first bits of all route paths.
Chris@0 12 */
Chris@0 13 class PathRootsSubscriber implements EventSubscriberInterface {
Chris@0 14
Chris@0 15 /**
Chris@0 16 * Stores the path roots available in the router.
Chris@0 17 *
Chris@0 18 * A path root is the first virtual directory of a path, like 'admin', 'node'
Chris@0 19 * or 'user'.
Chris@0 20 *
Chris@0 21 * @var array
Chris@0 22 */
Chris@0 23 protected $pathRoots = [];
Chris@0 24
Chris@0 25 /**
Chris@0 26 * The state key value store.
Chris@0 27 *
Chris@0 28 * @var \Drupal\Core\State\StateInterface
Chris@0 29 */
Chris@0 30 protected $state;
Chris@0 31
Chris@0 32 /**
Chris@0 33 * Constructs a new PathRootsSubscriber instance.
Chris@0 34 *
Chris@0 35 * @param \Drupal\Core\State\StateInterface $state
Chris@0 36 * The state key value store.
Chris@0 37 */
Chris@0 38 public function __construct(StateInterface $state) {
Chris@0 39 $this->state = $state;
Chris@0 40 }
Chris@0 41
Chris@0 42 /**
Chris@0 43 * Collects all path roots.
Chris@0 44 *
Chris@0 45 * @param \Drupal\Core\Routing\RouteBuildEvent $event
Chris@0 46 * The route build event.
Chris@0 47 */
Chris@0 48 public function onRouteAlter(RouteBuildEvent $event) {
Chris@0 49 $collection = $event->getRouteCollection();
Chris@0 50 foreach ($collection->all() as $route) {
Chris@0 51 $bits = explode('/', ltrim($route->getPath(), '/'));
Chris@0 52 $this->pathRoots[$bits[0]] = $bits[0];
Chris@0 53 }
Chris@0 54 }
Chris@0 55
Chris@0 56 /**
Chris@0 57 * {@inheritdoc}
Chris@0 58 */
Chris@0 59 public function onRouteFinished() {
Chris@0 60 $this->state->set('router.path_roots', array_keys($this->pathRoots));
Chris@0 61 $this->pathRoots = [];
Chris@0 62 }
Chris@0 63
Chris@0 64 /**
Chris@0 65 * {@inheritdoc}
Chris@0 66 */
Chris@0 67 public static function getSubscribedEvents() {
Chris@0 68 $events = [];
Chris@0 69 // Try to set a low priority to ensure that all routes are already added.
Chris@0 70 $events[RoutingEvents::ALTER][] = ['onRouteAlter', -1024];
Chris@0 71 $events[RoutingEvents::FINISHED][] = ['onRouteFinished'];
Chris@0 72 return $events;
Chris@0 73 }
Chris@0 74
Chris@0 75 }