3 namespace Drupal\Core\Routing;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Cache\CacheBackendInterface;
8 use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
9 use Drupal\Core\Path\CurrentPathStack;
10 use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
11 use Drupal\Core\State\StateInterface;
12 use Symfony\Cmf\Component\Routing\PagedRouteCollection;
13 use Symfony\Cmf\Component\Routing\PagedRouteProviderInterface;
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\Routing\Exception\RouteNotFoundException;
17 use Symfony\Component\Routing\RouteCollection;
18 use \Drupal\Core\Database\Connection;
21 * A Route Provider front-end for all Drupal-stored routes.
23 class RouteProvider implements PreloadableRouteProviderInterface, PagedRouteProviderInterface, EventSubscriberInterface {
26 * The database connection from which to read route information.
28 * @var \Drupal\Core\Database\Connection
30 protected $connection;
33 * The name of the SQL table from which to read the routes.
42 * @var \Drupal\Core\State\StateInterface
47 * A cache of already-loaded routes, keyed by route name.
49 * @var \Symfony\Component\Routing\Route[]
51 protected $routes = [];
54 * A cache of already-loaded serialized routes, keyed by route name.
58 protected $serializedRoutes = [];
63 * @var \Drupal\Core\Path\CurrentPathStack
65 protected $currentPath;
70 * @var \Drupal\Core\Cache\CacheBackendInterface
75 * The cache tag invalidator.
77 * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
79 protected $cacheTagInvalidator;
82 * A path processor manager for resolving the system path.
84 * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface
86 protected $pathProcessor;
89 * Cache ID prefix used to load routes.
91 const ROUTE_LOAD_CID_PREFIX = 'route_provider.route_load:';
94 * Constructs a new PathMatcher.
96 * @param \Drupal\Core\Database\Connection $connection
97 * A database connection object.
98 * @param \Drupal\Core\State\StateInterface $state
100 * @param \Drupal\Core\Path\CurrentPathStack $current_path
102 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
104 * @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor
105 * The path processor.
106 * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tag_invalidator
107 * The cache tag invalidator.
108 * @param string $table
109 * (Optional) The table in the database to use for matching. Defaults to 'router'
111 public function __construct(Connection $connection, StateInterface $state, CurrentPathStack $current_path, CacheBackendInterface $cache_backend, InboundPathProcessorInterface $path_processor, CacheTagsInvalidatorInterface $cache_tag_invalidator, $table = 'router') {
112 $this->connection = $connection;
113 $this->state = $state;
114 $this->currentPath = $current_path;
115 $this->cache = $cache_backend;
116 $this->cacheTagInvalidator = $cache_tag_invalidator;
117 $this->pathProcessor = $path_processor;
118 $this->tableName = $table;
122 * Finds routes that may potentially match the request.
124 * This may return a mixed list of class instances, but all routes returned
125 * must extend the core symfony route. The classes may also implement
126 * RouteObjectInterface to link to a content document.
128 * This method may not throw an exception based on implementation specific
129 * restrictions on the url. That case is considered a not found - returning
130 * an empty array. Exceptions are only used to abort the whole request in
131 * case something is seriously broken, like the storage backend being down.
133 * Note that implementations may not implement an optimal matching
134 * algorithm, simply a reasonable first pass. That allows for potentially
135 * very large route sets to be filtered down to likely candidates, which
136 * may then be filtered in memory more completely.
138 * @param Request $request
139 * A request against which to match.
141 * @return \Symfony\Component\Routing\RouteCollection with all urls that
142 * could potentially match $request. Empty collection if nothing can
143 * match. The collection will be sorted from highest to lowest fit (match
144 * of path parts) and then in ascending order by route name for routes
147 public function getRouteCollectionForRequest(Request $request) {
148 // Cache both the system path as well as route parameters and matching
150 $cid = 'route:' . $request->getPathInfo() . ':' . $request->getQueryString();
151 if ($cached = $this->cache->get($cid)) {
152 $this->currentPath->setPath($cached->data['path'], $request);
153 $request->query->replace($cached->data['query']);
154 return $cached->data['routes'];
157 // Just trim on the right side.
158 $path = $request->getPathInfo();
159 $path = $path === '/' ? $path : rtrim($request->getPathInfo(), '/');
160 $path = $this->pathProcessor->processInbound($path, $request);
161 $this->currentPath->setPath($path, $request);
162 // Incoming path processors may also set query parameters.
163 $query_parameters = $request->query->all();
164 $routes = $this->getRoutesByPath(rtrim($path, '/'));
167 'query' => $query_parameters,
170 $this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']);
176 * Find the route using the provided route name (and parameters).
178 * @param string $name
179 * The route name to fetch
181 * @return \Symfony\Component\Routing\Route
184 * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
185 * Thrown if there is no route with that name in this repository.
187 public function getRouteByName($name) {
188 $routes = $this->getRoutesByNames([$name]);
189 if (empty($routes)) {
190 throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
193 return reset($routes);
199 public function preLoadRoutes($names) {
201 throw new \InvalidArgumentException('You must specify the route names to load');
204 $routes_to_load = array_diff($names, array_keys($this->routes), array_keys($this->serializedRoutes));
205 if ($routes_to_load) {
207 $cid = static::ROUTE_LOAD_CID_PREFIX . hash('sha512', serialize($routes_to_load));
208 if ($cache = $this->cache->get($cid)) {
209 $routes = $cache->data;
213 $result = $this->connection->query('SELECT name, route FROM {' . $this->connection->escapeTable($this->tableName) . '} WHERE name IN ( :names[] )', [':names[]' => $routes_to_load]);
214 $routes = $result->fetchAllKeyed();
216 $this->cache->set($cid, $routes, Cache::PERMANENT, ['routes']);
218 catch (\Exception $e) {
223 $this->serializedRoutes += $routes;
230 public function getRoutesByNames($names) {
231 $this->preLoadRoutes($names);
233 foreach ($names as $name) {
234 // The specified route name might not exist or might be serialized.
235 if (!isset($this->routes[$name]) && isset($this->serializedRoutes[$name])) {
236 $this->routes[$name] = unserialize($this->serializedRoutes[$name]);
237 unset($this->serializedRoutes[$name]);
241 return array_intersect_key($this->routes, array_flip($names));
245 * Returns an array of path pattern outlines that could match the path parts.
247 * @param array $parts
248 * The parts of the path for which we want candidates.
251 * An array of outlines that could match the specified path parts.
253 protected function getCandidateOutlines(array $parts) {
254 $number_parts = count($parts);
256 $length = $number_parts - 1;
257 $end = (1 << $number_parts) - 1;
259 // The highest possible mask is a 1 bit for every part of the path. We will
260 // check every value down from there to generate a possible outline.
261 if ($number_parts == 1) {
264 elseif ($number_parts <= 3 && $number_parts > 0) {
265 // Optimization - don't query the state system for short paths. This also
266 // insulates against the state entry for masks going missing for common
267 // user-facing paths since we generate all values without checking state.
268 $masks = range($end, 1);
270 elseif ($number_parts <= 0) {
271 // No path can match, short-circuit the process.
275 // Get the actual patterns that exist out of state.
276 $masks = (array) $this->state->get('routing.menu_masks.' . $this->tableName, []);
279 // Only examine patterns that actually exist as router items (the masks).
280 foreach ($masks as $i) {
282 // Only look at masks that are not longer than the path of interest.
285 elseif ($i < (1 << $length)) {
286 // We have exhausted the masks of a given length, so decrease the length.
290 for ($j = $length; $j >= 0; $j--) {
291 // Check the bit on the $j offset.
292 if ($i & (1 << $j)) {
293 // Bit one means the original value.
294 $current .= $parts[$length - $j];
297 // Bit zero means means wildcard.
300 // Unless we are at offset 0, add a slash.
305 $ancestors[] = '/' . $current;
313 public function getRoutesByPattern($pattern) {
314 $path = RouteCompiler::getPatternOutline($pattern);
316 return $this->getRoutesByPath($path);
320 * Get all routes which match a certain pattern.
322 * @param string $path
323 * The route pattern to search for.
325 * @return \Symfony\Component\Routing\RouteCollection
326 * Returns a route collection of matching routes. The collection may be
327 * empty and will be sorted from highest to lowest fit (match of path parts)
328 * and then in ascending order by route name for routes with the same fit.
330 protected function getRoutesByPath($path) {
331 // Split the path up on the slashes, ignoring multiple slashes in a row
332 // or leading or trailing slashes. Convert to lower case here so we can
333 // have a case-insensitive match from the incoming path to the lower case
334 // pattern outlines from \Drupal\Core\Routing\RouteCompiler::compile().
335 // @see \Drupal\Core\Routing\CompiledRoute::__construct()
336 $parts = preg_split('@/+@', Unicode::strtolower($path), NULL, PREG_SPLIT_NO_EMPTY);
338 $collection = new RouteCollection();
340 $ancestors = $this->getCandidateOutlines($parts);
341 if (empty($ancestors)) {
345 // The >= check on number_parts allows us to match routes with optional
346 // trailing wildcard parts as long as the pattern matches, since we
347 // dump the route pattern without those optional parts.
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", [
350 ':patterns[]' => $ancestors, ':count_parts' => count($parts),
352 ->fetchAll(\PDO::FETCH_ASSOC);
354 catch (\Exception $e) {
358 // We sort by fit and name in PHP to avoid a SQL filesort and avoid any
359 // difference in the sorting behavior of SQL back-ends.
360 usort($routes, [$this, 'routeProviderRouteCompare']);
362 foreach ($routes as $row) {
363 $collection->add($row['name'], unserialize($row['route']));
370 * Comparison function for usort on routes.
372 protected function routeProviderRouteCompare(array $a, array $b) {
373 if ($a['fit'] == $b['fit']) {
374 return strcmp($a['name'], $b['name']);
376 // Reverse sort from highest to lowest fit. PHP should cast to int, but
377 // the explicit cast makes this sort more robust against unexpected input.
378 return (int) $a['fit'] < (int) $b['fit'] ? 1 : -1;
384 public function getAllRoutes() {
385 return new PagedRouteCollection($this);
391 public function reset() {
393 $this->serializedRoutes = [];
394 $this->cacheTagInvalidator->invalidateTags(['routes']);
400 public static function getSubscribedEvents() {
401 $events[RoutingEvents::FINISHED][] = ['reset'];
408 public function getRoutesPaged($offset, $length = NULL) {
409 $select = $this->connection->select($this->tableName, 'router')
410 ->fields('router', ['name', 'route']);
412 if (isset($length)) {
413 $select->range($offset, $length);
416 $routes = $select->execute()->fetchAllKeyed();
419 foreach ($routes as $name => $route) {
420 $result[$name] = unserialize($route);
429 public function getRoutesCount() {
430 return $this->connection->query("SELECT COUNT(*) FROM {" . $this->connection->escapeTable($this->tableName) . "}")->fetchField();