RouteProvider.php 15 KB

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