annotate core/lib/Drupal/Core/Routing/RouteProvider.php @ 12:7a779792577d

Update Drupal core to v8.4.5 (via Composer)
author Chris Cannam
date Fri, 23 Feb 2018 15:52:07 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Routing;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\Unicode;
Chris@0 6 use Drupal\Core\Cache\Cache;
Chris@0 7 use Drupal\Core\Cache\CacheBackendInterface;
Chris@0 8 use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
Chris@0 9 use Drupal\Core\Path\CurrentPathStack;
Chris@0 10 use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
Chris@0 11 use Drupal\Core\State\StateInterface;
Chris@0 12 use Symfony\Cmf\Component\Routing\PagedRouteCollection;
Chris@0 13 use Symfony\Cmf\Component\Routing\PagedRouteProviderInterface;
Chris@0 14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
Chris@0 15 use Symfony\Component\HttpFoundation\Request;
Chris@0 16 use Symfony\Component\Routing\Exception\RouteNotFoundException;
Chris@0 17 use Symfony\Component\Routing\RouteCollection;
Chris@0 18 use Drupal\Core\Database\Connection;
Chris@0 19
Chris@0 20 /**
Chris@0 21 * A Route Provider front-end for all Drupal-stored routes.
Chris@0 22 */
Chris@0 23 class RouteProvider implements PreloadableRouteProviderInterface, PagedRouteProviderInterface, EventSubscriberInterface {
Chris@0 24
Chris@0 25 /**
Chris@0 26 * The database connection from which to read route information.
Chris@0 27 *
Chris@0 28 * @var \Drupal\Core\Database\Connection
Chris@0 29 */
Chris@0 30 protected $connection;
Chris@0 31
Chris@0 32 /**
Chris@0 33 * The name of the SQL table from which to read the routes.
Chris@0 34 *
Chris@0 35 * @var string
Chris@0 36 */
Chris@0 37 protected $tableName;
Chris@0 38
Chris@0 39 /**
Chris@0 40 * The state.
Chris@0 41 *
Chris@0 42 * @var \Drupal\Core\State\StateInterface
Chris@0 43 */
Chris@0 44 protected $state;
Chris@0 45
Chris@0 46 /**
Chris@0 47 * A cache of already-loaded routes, keyed by route name.
Chris@0 48 *
Chris@0 49 * @var \Symfony\Component\Routing\Route[]
Chris@0 50 */
Chris@0 51 protected $routes = [];
Chris@0 52
Chris@0 53 /**
Chris@0 54 * A cache of already-loaded serialized routes, keyed by route name.
Chris@0 55 *
Chris@0 56 * @var string[]
Chris@0 57 */
Chris@0 58 protected $serializedRoutes = [];
Chris@0 59
Chris@0 60 /**
Chris@0 61 * The current path.
Chris@0 62 *
Chris@0 63 * @var \Drupal\Core\Path\CurrentPathStack
Chris@0 64 */
Chris@0 65 protected $currentPath;
Chris@0 66
Chris@0 67 /**
Chris@0 68 * The cache backend.
Chris@0 69 *
Chris@0 70 * @var \Drupal\Core\Cache\CacheBackendInterface
Chris@0 71 */
Chris@0 72 protected $cache;
Chris@0 73
Chris@0 74 /**
Chris@0 75 * The cache tag invalidator.
Chris@0 76 *
Chris@0 77 * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
Chris@0 78 */
Chris@0 79 protected $cacheTagInvalidator;
Chris@0 80
Chris@0 81 /**
Chris@0 82 * A path processor manager for resolving the system path.
Chris@0 83 *
Chris@0 84 * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface
Chris@0 85 */
Chris@0 86 protected $pathProcessor;
Chris@0 87
Chris@0 88 /**
Chris@0 89 * Cache ID prefix used to load routes.
Chris@0 90 */
Chris@0 91 const ROUTE_LOAD_CID_PREFIX = 'route_provider.route_load:';
Chris@0 92
Chris@0 93 /**
Chris@0 94 * Constructs a new PathMatcher.
Chris@0 95 *
Chris@0 96 * @param \Drupal\Core\Database\Connection $connection
Chris@0 97 * A database connection object.
Chris@0 98 * @param \Drupal\Core\State\StateInterface $state
Chris@0 99 * The state.
Chris@0 100 * @param \Drupal\Core\Path\CurrentPathStack $current_path
Chris@0 101 * The current path.
Chris@0 102 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
Chris@0 103 * The cache backend.
Chris@0 104 * @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor
Chris@0 105 * The path processor.
Chris@0 106 * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tag_invalidator
Chris@0 107 * The cache tag invalidator.
Chris@0 108 * @param string $table
Chris@0 109 * (Optional) The table in the database to use for matching. Defaults to 'router'
Chris@0 110 */
Chris@0 111 public function __construct(Connection $connection, StateInterface $state, CurrentPathStack $current_path, CacheBackendInterface $cache_backend, InboundPathProcessorInterface $path_processor, CacheTagsInvalidatorInterface $cache_tag_invalidator, $table = 'router') {
Chris@0 112 $this->connection = $connection;
Chris@0 113 $this->state = $state;
Chris@0 114 $this->currentPath = $current_path;
Chris@0 115 $this->cache = $cache_backend;
Chris@0 116 $this->cacheTagInvalidator = $cache_tag_invalidator;
Chris@0 117 $this->pathProcessor = $path_processor;
Chris@0 118 $this->tableName = $table;
Chris@0 119 }
Chris@0 120
Chris@0 121 /**
Chris@0 122 * Finds routes that may potentially match the request.
Chris@0 123 *
Chris@0 124 * This may return a mixed list of class instances, but all routes returned
Chris@0 125 * must extend the core symfony route. The classes may also implement
Chris@0 126 * RouteObjectInterface to link to a content document.
Chris@0 127 *
Chris@0 128 * This method may not throw an exception based on implementation specific
Chris@0 129 * restrictions on the url. That case is considered a not found - returning
Chris@0 130 * an empty array. Exceptions are only used to abort the whole request in
Chris@0 131 * case something is seriously broken, like the storage backend being down.
Chris@0 132 *
Chris@0 133 * Note that implementations may not implement an optimal matching
Chris@0 134 * algorithm, simply a reasonable first pass. That allows for potentially
Chris@0 135 * very large route sets to be filtered down to likely candidates, which
Chris@0 136 * may then be filtered in memory more completely.
Chris@0 137 *
Chris@12 138 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 139 * A request against which to match.
Chris@0 140 *
Chris@0 141 * @return \Symfony\Component\Routing\RouteCollection
Chris@0 142 * RouteCollection with all urls that could potentially match $request.
Chris@0 143 * Empty collection if nothing can match. The collection will be sorted from
Chris@0 144 * highest to lowest fit (match of path parts) and then in ascending order
Chris@0 145 * by route name for routes with the same fit.
Chris@0 146 */
Chris@0 147 public function getRouteCollectionForRequest(Request $request) {
Chris@0 148 // Cache both the system path as well as route parameters and matching
Chris@0 149 // routes.
Chris@0 150 $cid = 'route:' . $request->getPathInfo() . ':' . $request->getQueryString();
Chris@0 151 if ($cached = $this->cache->get($cid)) {
Chris@0 152 $this->currentPath->setPath($cached->data['path'], $request);
Chris@0 153 $request->query->replace($cached->data['query']);
Chris@0 154 return $cached->data['routes'];
Chris@0 155 }
Chris@0 156 else {
Chris@0 157 // Just trim on the right side.
Chris@0 158 $path = $request->getPathInfo();
Chris@0 159 $path = $path === '/' ? $path : rtrim($request->getPathInfo(), '/');
Chris@0 160 $path = $this->pathProcessor->processInbound($path, $request);
Chris@0 161 $this->currentPath->setPath($path, $request);
Chris@0 162 // Incoming path processors may also set query parameters.
Chris@0 163 $query_parameters = $request->query->all();
Chris@0 164 $routes = $this->getRoutesByPath(rtrim($path, '/'));
Chris@0 165 $cache_value = [
Chris@0 166 'path' => $path,
Chris@0 167 'query' => $query_parameters,
Chris@0 168 'routes' => $routes,
Chris@0 169 ];
Chris@0 170 $this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']);
Chris@0 171 return $routes;
Chris@0 172 }
Chris@0 173 }
Chris@0 174
Chris@0 175 /**
Chris@0 176 * Find the route using the provided route name (and parameters).
Chris@0 177 *
Chris@0 178 * @param string $name
Chris@0 179 * The route name to fetch
Chris@0 180 *
Chris@0 181 * @return \Symfony\Component\Routing\Route
Chris@0 182 * The found route.
Chris@0 183 *
Chris@0 184 * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
Chris@0 185 * Thrown if there is no route with that name in this repository.
Chris@0 186 */
Chris@0 187 public function getRouteByName($name) {
Chris@0 188 $routes = $this->getRoutesByNames([$name]);
Chris@0 189 if (empty($routes)) {
Chris@0 190 throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
Chris@0 191 }
Chris@0 192
Chris@0 193 return reset($routes);
Chris@0 194 }
Chris@0 195
Chris@0 196 /**
Chris@0 197 * {@inheritdoc}
Chris@0 198 */
Chris@0 199 public function preLoadRoutes($names) {
Chris@0 200 if (empty($names)) {
Chris@0 201 throw new \InvalidArgumentException('You must specify the route names to load');
Chris@0 202 }
Chris@0 203
Chris@0 204 $routes_to_load = array_diff($names, array_keys($this->routes), array_keys($this->serializedRoutes));
Chris@0 205 if ($routes_to_load) {
Chris@0 206
Chris@0 207 $cid = static::ROUTE_LOAD_CID_PREFIX . hash('sha512', serialize($routes_to_load));
Chris@0 208 if ($cache = $this->cache->get($cid)) {
Chris@0 209 $routes = $cache->data;
Chris@0 210 }
Chris@0 211 else {
Chris@0 212 try {
Chris@0 213 $result = $this->connection->query('SELECT name, route FROM {' . $this->connection->escapeTable($this->tableName) . '} WHERE name IN ( :names[] )', [':names[]' => $routes_to_load]);
Chris@0 214 $routes = $result->fetchAllKeyed();
Chris@0 215
Chris@0 216 $this->cache->set($cid, $routes, Cache::PERMANENT, ['routes']);
Chris@0 217 }
Chris@0 218 catch (\Exception $e) {
Chris@0 219 $routes = [];
Chris@0 220 }
Chris@0 221 }
Chris@0 222
Chris@0 223 $this->serializedRoutes += $routes;
Chris@0 224 }
Chris@0 225 }
Chris@0 226
Chris@0 227 /**
Chris@0 228 * {@inheritdoc}
Chris@0 229 */
Chris@0 230 public function getRoutesByNames($names) {
Chris@0 231 $this->preLoadRoutes($names);
Chris@0 232
Chris@0 233 foreach ($names as $name) {
Chris@0 234 // The specified route name might not exist or might be serialized.
Chris@0 235 if (!isset($this->routes[$name]) && isset($this->serializedRoutes[$name])) {
Chris@0 236 $this->routes[$name] = unserialize($this->serializedRoutes[$name]);
Chris@0 237 unset($this->serializedRoutes[$name]);
Chris@0 238 }
Chris@0 239 }
Chris@0 240
Chris@0 241 return array_intersect_key($this->routes, array_flip($names));
Chris@0 242 }
Chris@0 243
Chris@0 244 /**
Chris@0 245 * Returns an array of path pattern outlines that could match the path parts.
Chris@0 246 *
Chris@0 247 * @param array $parts
Chris@0 248 * The parts of the path for which we want candidates.
Chris@0 249 *
Chris@0 250 * @return array
Chris@0 251 * An array of outlines that could match the specified path parts.
Chris@0 252 */
Chris@0 253 protected function getCandidateOutlines(array $parts) {
Chris@0 254 $number_parts = count($parts);
Chris@0 255 $ancestors = [];
Chris@0 256 $length = $number_parts - 1;
Chris@0 257 $end = (1 << $number_parts) - 1;
Chris@0 258
Chris@0 259 // The highest possible mask is a 1 bit for every part of the path. We will
Chris@0 260 // check every value down from there to generate a possible outline.
Chris@0 261 if ($number_parts == 1) {
Chris@0 262 $masks = [1];
Chris@0 263 }
Chris@0 264 elseif ($number_parts <= 3 && $number_parts > 0) {
Chris@0 265 // Optimization - don't query the state system for short paths. This also
Chris@0 266 // insulates against the state entry for masks going missing for common
Chris@0 267 // user-facing paths since we generate all values without checking state.
Chris@0 268 $masks = range($end, 1);
Chris@0 269 }
Chris@0 270 elseif ($number_parts <= 0) {
Chris@0 271 // No path can match, short-circuit the process.
Chris@0 272 $masks = [];
Chris@0 273 }
Chris@0 274 else {
Chris@0 275 // Get the actual patterns that exist out of state.
Chris@0 276 $masks = (array) $this->state->get('routing.menu_masks.' . $this->tableName, []);
Chris@0 277 }
Chris@0 278
Chris@0 279 // Only examine patterns that actually exist as router items (the masks).
Chris@0 280 foreach ($masks as $i) {
Chris@0 281 if ($i > $end) {
Chris@0 282 // Only look at masks that are not longer than the path of interest.
Chris@0 283 continue;
Chris@0 284 }
Chris@0 285 elseif ($i < (1 << $length)) {
Chris@0 286 // We have exhausted the masks of a given length, so decrease the length.
Chris@0 287 --$length;
Chris@0 288 }
Chris@0 289 $current = '';
Chris@0 290 for ($j = $length; $j >= 0; $j--) {
Chris@0 291 // Check the bit on the $j offset.
Chris@0 292 if ($i & (1 << $j)) {
Chris@0 293 // Bit one means the original value.
Chris@0 294 $current .= $parts[$length - $j];
Chris@0 295 }
Chris@0 296 else {
Chris@0 297 // Bit zero means means wildcard.
Chris@0 298 $current .= '%';
Chris@0 299 }
Chris@0 300 // Unless we are at offset 0, add a slash.
Chris@0 301 if ($j) {
Chris@0 302 $current .= '/';
Chris@0 303 }
Chris@0 304 }
Chris@0 305 $ancestors[] = '/' . $current;
Chris@0 306 }
Chris@0 307 return $ancestors;
Chris@0 308 }
Chris@0 309
Chris@0 310 /**
Chris@0 311 * {@inheritdoc}
Chris@0 312 */
Chris@0 313 public function getRoutesByPattern($pattern) {
Chris@0 314 $path = RouteCompiler::getPatternOutline($pattern);
Chris@0 315
Chris@0 316 return $this->getRoutesByPath($path);
Chris@0 317 }
Chris@0 318
Chris@0 319 /**
Chris@0 320 * Get all routes which match a certain pattern.
Chris@0 321 *
Chris@0 322 * @param string $path
Chris@0 323 * The route pattern to search for.
Chris@0 324 *
Chris@0 325 * @return \Symfony\Component\Routing\RouteCollection
Chris@0 326 * Returns a route collection of matching routes. The collection may be
Chris@0 327 * empty and will be sorted from highest to lowest fit (match of path parts)
Chris@0 328 * and then in ascending order by route name for routes with the same fit.
Chris@0 329 */
Chris@0 330 protected function getRoutesByPath($path) {
Chris@0 331 // Split the path up on the slashes, ignoring multiple slashes in a row
Chris@0 332 // or leading or trailing slashes. Convert to lower case here so we can
Chris@0 333 // have a case-insensitive match from the incoming path to the lower case
Chris@0 334 // pattern outlines from \Drupal\Core\Routing\RouteCompiler::compile().
Chris@0 335 // @see \Drupal\Core\Routing\CompiledRoute::__construct()
Chris@0 336 $parts = preg_split('@/+@', Unicode::strtolower($path), NULL, PREG_SPLIT_NO_EMPTY);
Chris@0 337
Chris@0 338 $collection = new RouteCollection();
Chris@0 339
Chris@0 340 $ancestors = $this->getCandidateOutlines($parts);
Chris@0 341 if (empty($ancestors)) {
Chris@0 342 return $collection;
Chris@0 343 }
Chris@0 344
Chris@0 345 // The >= check on number_parts allows us to match routes with optional
Chris@0 346 // trailing wildcard parts as long as the pattern matches, since we
Chris@0 347 // dump the route pattern without those optional parts.
Chris@0 348 try {
Chris@0 349 $routes = $this->connection->query("SELECT name, route, fit FROM {" . $this->connection->escapeTable($this->tableName) . "} WHERE pattern_outline IN ( :patterns[] ) AND number_parts >= :count_parts", [
Chris@0 350 ':patterns[]' => $ancestors,
Chris@0 351 ':count_parts' => count($parts),
Chris@0 352 ])
Chris@0 353 ->fetchAll(\PDO::FETCH_ASSOC);
Chris@0 354 }
Chris@0 355 catch (\Exception $e) {
Chris@0 356 $routes = [];
Chris@0 357 }
Chris@0 358
Chris@0 359 // We sort by fit and name in PHP to avoid a SQL filesort and avoid any
Chris@0 360 // difference in the sorting behavior of SQL back-ends.
Chris@0 361 usort($routes, [$this, 'routeProviderRouteCompare']);
Chris@0 362
Chris@0 363 foreach ($routes as $row) {
Chris@0 364 $collection->add($row['name'], unserialize($row['route']));
Chris@0 365 }
Chris@0 366
Chris@0 367 return $collection;
Chris@0 368 }
Chris@0 369
Chris@0 370 /**
Chris@0 371 * Comparison function for usort on routes.
Chris@0 372 */
Chris@0 373 protected function routeProviderRouteCompare(array $a, array $b) {
Chris@0 374 if ($a['fit'] == $b['fit']) {
Chris@0 375 return strcmp($a['name'], $b['name']);
Chris@0 376 }
Chris@0 377 // Reverse sort from highest to lowest fit. PHP should cast to int, but
Chris@0 378 // the explicit cast makes this sort more robust against unexpected input.
Chris@0 379 return (int) $a['fit'] < (int) $b['fit'] ? 1 : -1;
Chris@0 380 }
Chris@0 381
Chris@0 382 /**
Chris@0 383 * {@inheritdoc}
Chris@0 384 */
Chris@0 385 public function getAllRoutes() {
Chris@0 386 return new PagedRouteCollection($this);
Chris@0 387 }
Chris@0 388
Chris@0 389 /**
Chris@0 390 * {@inheritdoc}
Chris@0 391 */
Chris@0 392 public function reset() {
Chris@0 393 $this->routes = [];
Chris@0 394 $this->serializedRoutes = [];
Chris@0 395 $this->cacheTagInvalidator->invalidateTags(['routes']);
Chris@0 396 }
Chris@0 397
Chris@0 398 /**
Chris@0 399 * {@inheritdoc}
Chris@0 400 */
Chris@0 401 public static function getSubscribedEvents() {
Chris@0 402 $events[RoutingEvents::FINISHED][] = ['reset'];
Chris@0 403 return $events;
Chris@0 404 }
Chris@0 405
Chris@0 406 /**
Chris@0 407 * {@inheritdoc}
Chris@0 408 */
Chris@0 409 public function getRoutesPaged($offset, $length = NULL) {
Chris@0 410 $select = $this->connection->select($this->tableName, 'router')
Chris@0 411 ->fields('router', ['name', 'route']);
Chris@0 412
Chris@0 413 if (isset($length)) {
Chris@0 414 $select->range($offset, $length);
Chris@0 415 }
Chris@0 416
Chris@0 417 $routes = $select->execute()->fetchAllKeyed();
Chris@0 418
Chris@0 419 $result = [];
Chris@0 420 foreach ($routes as $name => $route) {
Chris@0 421 $result[$name] = unserialize($route);
Chris@0 422 }
Chris@0 423
Chris@0 424 return $result;
Chris@0 425 }
Chris@0 426
Chris@0 427 /**
Chris@0 428 * {@inheritdoc}
Chris@0 429 */
Chris@0 430 public function getRoutesCount() {
Chris@0 431 return $this->connection->query("SELECT COUNT(*) FROM {" . $this->connection->escapeTable($this->tableName) . "}")->fetchField();
Chris@0 432 }
Chris@0 433
Chris@0 434 }