RouteBuilder.php 7.08 KB
Newer Older
1 2
<?php

3 4
/**
 * @file
5
 * Contains \Drupal\Core\Routing\RouteBuilder.
6 7
 */

8 9
namespace Drupal\Core\Routing;

10
use Drupal\Component\Discovery\YamlDiscovery;
11
use Drupal\Core\Access\CheckProviderInterface;
12
use Drupal\Core\Controller\ControllerResolverInterface;
13 14
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Lock\LockBackendInterface;
15
use Drupal\Core\DestructableInterface;
16
use Symfony\Component\EventDispatcher\Event;
17 18 19 20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

21 22 23
/**
 * Managing class for rebuilding the router table.
 */
24
class RouteBuilder implements RouteBuilderInterface, DestructableInterface {
25

26 27 28
  /**
   * The dumper to which we should send collected routes.
   *
29
   * @var \Drupal\Core\Routing\MatcherDumperInterface
30
   */
31 32
  protected $dumper;

33 34 35 36 37 38 39
  /**
   * The used lock backend instance.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface $lock
   */
  protected $lock;

40 41 42 43 44 45 46
  /**
   * The event dispatcher to notify of routes.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $dispatcher;

47 48
  /**
   * The module handler.
49 50 51 52 53
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

54 55 56 57 58 59 60
  /**
   * The controller resolver.
   *
   * @var \Drupal\Core\Controller\ControllerResolverInterface
   */
  protected $controllerResolver;

61 62 63 64 65 66 67
  /**
   * The route collection during the rebuild.
   *
   * @var \Symfony\Component\Routing\RouteCollection
   */
  protected $routeCollection;

68
  /**
69
   * Flag that indicates if we are currently rebuilding the routes.
70 71 72 73 74
   *
   * @var bool
   */
  protected $building = FALSE;

75 76 77 78 79 80 81
  /**
   * Flag that indicates if we should rebuild at the end of the request.
   *
   * @var bool
   */
  protected $rebuildNeeded = FALSE;

82 83 84 85 86 87 88
  /**
   * The check provider.
   *
   * @var \Drupal\Core\Access\CheckProviderInterface
   */
  protected $checkProvider;

89
  /**
90
   * Constructs the RouteBuilder using the passed MatcherDumperInterface.
91
   *
92
   * @param \Drupal\Core\Routing\MatcherDumperInterface $dumper
93
   *   The matcher dumper used to store the route information.
94 95
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
96
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
97
   *   The event dispatcher to notify of routes.
98 99
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
100 101
   * @param \Drupal\Core\Controller\ControllerResolverInterface $controller_resolver
   *   The controller resolver.
102 103
   * @param \Drupal\Core\Access\CheckProviderInterface $check_provider
   *   The check provider.
104
   */
105
  public function __construct(MatcherDumperInterface $dumper, LockBackendInterface $lock, EventDispatcherInterface $dispatcher, ModuleHandlerInterface $module_handler, ControllerResolverInterface $controller_resolver, CheckProviderInterface $check_provider) {
106
    $this->dumper = $dumper;
107
    $this->lock = $lock;
108
    $this->dispatcher = $dispatcher;
109
    $this->moduleHandler = $module_handler;
110
    $this->controllerResolver = $controller_resolver;
111
    $this->checkProvider = $check_provider;
112 113
  }

114 115 116 117 118 119 120
  /**
   * {@inheritdoc}
   */
  public function setRebuildNeeded() {
    $this->rebuildNeeded = TRUE;
  }

121
  /**
122
   * {@inheritdoc}
123
   */
124
  public function rebuild() {
125 126 127 128
    if ($this->building) {
      throw new \RuntimeException('Recursive router rebuild detected.');
    }

129 130 131 132 133
    if (!$this->lock->acquire('router_rebuild')) {
      // Wait for another request that is already doing this work.
      // We choose to block here since otherwise the routes might not be
      // available, resulting in a 404.
      $this->lock->wait('router_rebuild');
134
      return FALSE;
135 136
    }

137 138
    $this->building = TRUE;

139 140
    $collection = new RouteCollection();
    foreach ($this->getRouteDefinitions() as $routes) {
141 142 143
      // The top-level 'routes_callback' is a list of methods in controller
      // syntax, see \Drupal\Core\Controller\ControllerResolver. These methods
      // should return a set of \Symfony\Component\Routing\Route objects, either
144 145 146 147
      // in an associative array keyed by the route name, which will be iterated
      // over and added to the collection for this provider, or as a new
      // \Symfony\Component\Routing\RouteCollection object, which will be added
      // to the collection.
148 149 150 151
      if (isset($routes['route_callbacks'])) {
        foreach ($routes['route_callbacks'] as $route_callback) {
          $callback = $this->controllerResolver->getControllerFromDefinition($route_callback);
          if ($callback_routes = call_user_func($callback)) {
152 153 154 155 156 157 158 159 160
            // If a RouteCollection is returned, add the whole collection.
            if ($callback_routes instanceof RouteCollection) {
              $collection->addCollection($callback_routes);
            }
            // Otherwise, add each Route object individually.
            else {
              foreach ($callback_routes as $name => $callback_route) {
                $collection->add($name, $callback_route);
              }
161 162 163 164 165
            }
          }
        }
        unset($routes['route_callbacks']);
      }
166 167 168 169 170 171 172
      foreach ($routes as $name => $route_info) {
        $route_info += array(
          'defaults' => array(),
          'requirements' => array(),
          'options' => array(),
        );

173
        $route = new Route($route_info['path'], $route_info['defaults'], $route_info['requirements'], $route_info['options']);
174
        $collection->add($name, $route);
175
      }
176
    }
177

178 179 180 181 182 183 184 185 186
    // DYNAMIC is supposed to be used to add new routes based upon all the
    // static defined ones.
    $this->dispatcher->dispatch(RoutingEvents::DYNAMIC, new RouteBuildEvent($collection));

    // ALTER is the final step to alter all the existing routes. We cannot stop
    // people from adding new routes here, but we define two separate steps to
    // make it clear.
    $this->dispatcher->dispatch(RoutingEvents::ALTER, new RouteBuildEvent($collection));

187 188
    $this->checkProvider->setChecks($collection);

189
    $this->dumper->addRoutes($collection);
190
    $this->dumper->dump();
191

192
    $this->lock->release('router_rebuild');
193
    $this->dispatcher->dispatch(RoutingEvents::FINISHED, new Event());
194
    $this->building = FALSE;
195

196
    $this->rebuildNeeded = FALSE;
197

198 199 200
    return TRUE;
  }

201 202 203 204
  /**
   * {@inheritdoc}
   */
  public function rebuildIfNeeded() {
205
    if ($this->rebuildNeeded) {
206 207 208 209 210 211 212 213
      return $this->rebuild();
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
214 215 216 217 218
  public function destruct() {
    // Rebuild routes only once at the end of the request lifecycle to not
    // trigger multiple rebuilds and also make the page more responsive for the
    // user.
    $this->rebuildIfNeeded();
219 220
  }

221
  /**
222
   * Retrieves all defined routes from .routing.yml files.
223
   *
224 225
   * @return array
   *   The defined routes, keyed by provider.
226
   */
227
  protected function getRouteDefinitions() {
228 229 230 231
    // Always instantiate a new YamlDiscovery object so that we always search on
    // the up-to-date list of modules.
    $discovery = new YamlDiscovery('routing', $this->moduleHandler->getModuleDirectories());
    return $discovery->findAll();
232 233 234
  }

}