PathRootsSubscriber.php 1.8 KB

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