summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/EventSubscriber/PathRootsSubscriber.php
blob: 508e111650b4169e6b7f300b9b2ca8d09fa480f5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php

namespace Drupal\Core\EventSubscriber;

use Drupal\Core\State\StateInterface;
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Provides all available first bits of all route paths.
 */
class PathRootsSubscriber implements EventSubscriberInterface {

  /**
   * Stores the path roots available in the router.
   *
   * A path root is the first virtual directory of a path, like 'admin', 'node'
   * or 'user'.
   *
   * @var array
   */
  protected $pathRoots = [];

  /**
   * The state key value store.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Constructs a new PathRootsSubscriber instance.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state key value store.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * Collects all path roots.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The route build event.
   */
  public function onRouteAlter(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();
    foreach ($collection->all() as $route) {
      $bits = explode('/', ltrim($route->getPath(), '/'));
      $this->pathRoots[$bits[0]] = $bits[0];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function onRouteFinished() {
    $this->state->set('router.path_roots', array_keys($this->pathRoots));
    $this->pathRoots = [];
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = [];
    // Try to set a low priority to ensure that all routes are already added.
    $events[RoutingEvents::ALTER][] = ['onRouteAlter', -1024];
    $events[RoutingEvents::FINISHED][] = ['onRouteFinished'];
    return $events;
  }

}