CompiledUrlMatcherDumper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing\Matcher\Dumper;
  11. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  12. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  13. use Symfony\Component\Routing\Route;
  14. use Symfony\Component\Routing\RouteCollection;
  15. /**
  16. * CompiledUrlMatcherDumper creates PHP arrays to be used with CompiledUrlMatcher.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. * @author Tobias Schultze <http://tobion.de>
  20. * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. */
  23. class CompiledUrlMatcherDumper extends MatcherDumper
  24. {
  25. private $expressionLanguage;
  26. private $signalingException;
  27. /**
  28. * @var ExpressionFunctionProviderInterface[]
  29. */
  30. private $expressionLanguageProviders = [];
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function dump(array $options = [])
  35. {
  36. return <<<EOF
  37. <?php
  38. /**
  39. * This file has been auto-generated
  40. * by the Symfony Routing Component.
  41. */
  42. return [
  43. {$this->generateCompiledRoutes()}];
  44. EOF;
  45. }
  46. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  47. {
  48. $this->expressionLanguageProviders[] = $provider;
  49. }
  50. /**
  51. * Generates the arrays for CompiledUrlMatcher's constructor.
  52. */
  53. public function getCompiledRoutes(bool $forDump = false): array
  54. {
  55. // Group hosts by same-suffix, re-order when possible
  56. $matchHost = false;
  57. $routes = new StaticPrefixCollection();
  58. foreach ($this->getRoutes()->all() as $name => $route) {
  59. if ($host = $route->getHost()) {
  60. $matchHost = true;
  61. $host = '/'.strtr(strrev($host), '}.{', '(/)');
  62. }
  63. $routes->addRoute($host ?: '/(.*)', [$name, $route]);
  64. }
  65. if ($matchHost) {
  66. $compiledRoutes = [true];
  67. $routes = $routes->populateCollection(new RouteCollection());
  68. } else {
  69. $compiledRoutes = [false];
  70. $routes = $this->getRoutes();
  71. }
  72. [$staticRoutes, $dynamicRoutes] = $this->groupStaticRoutes($routes);
  73. $conditions = [null];
  74. $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes, $conditions);
  75. $chunkLimit = \count($dynamicRoutes);
  76. while (true) {
  77. try {
  78. $this->signalingException = new \RuntimeException('Compilation failed: regular expression is too large');
  79. $compiledRoutes = array_merge($compiledRoutes, $this->compileDynamicRoutes($dynamicRoutes, $matchHost, $chunkLimit, $conditions));
  80. break;
  81. } catch (\Exception $e) {
  82. if (1 < $chunkLimit && $this->signalingException === $e) {
  83. $chunkLimit = 1 + ($chunkLimit >> 1);
  84. continue;
  85. }
  86. throw $e;
  87. }
  88. }
  89. if ($forDump) {
  90. $compiledRoutes[2] = $compiledRoutes[4];
  91. }
  92. unset($conditions[0]);
  93. if ($conditions) {
  94. foreach ($conditions as $expression => $condition) {
  95. $conditions[$expression] = "case {$condition}: return {$expression};";
  96. }
  97. $checkConditionCode = <<<EOF
  98. static function (\$condition, \$context, \$request) { // \$checkCondition
  99. switch (\$condition) {
  100. {$this->indent(implode("\n", $conditions), 3)}
  101. }
  102. }
  103. EOF;
  104. $compiledRoutes[4] = $forDump ? $checkConditionCode.",\n" : eval('return '.$checkConditionCode.';');
  105. } else {
  106. $compiledRoutes[4] = $forDump ? " null, // \$checkCondition\n" : null;
  107. }
  108. return $compiledRoutes;
  109. }
  110. private function generateCompiledRoutes(): string
  111. {
  112. [$matchHost, $staticRoutes, $regexpCode, $dynamicRoutes, $checkConditionCode] = $this->getCompiledRoutes(true);
  113. $code = self::export($matchHost).', // $matchHost'."\n";
  114. $code .= '[ // $staticRoutes'."\n";
  115. foreach ($staticRoutes as $path => $routes) {
  116. $code .= sprintf(" %s => [\n", self::export($path));
  117. foreach ($routes as $route) {
  118. $code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
  119. }
  120. $code .= " ],\n";
  121. }
  122. $code .= "],\n";
  123. $code .= sprintf("[ // \$regexpList%s\n],\n", $regexpCode);
  124. $code .= '[ // $dynamicRoutes'."\n";
  125. foreach ($dynamicRoutes as $path => $routes) {
  126. $code .= sprintf(" %s => [\n", self::export($path));
  127. foreach ($routes as $route) {
  128. $code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
  129. }
  130. $code .= " ],\n";
  131. }
  132. $code .= "],\n";
  133. $code = preg_replace('/ => \[\n (\[.+?),\n \],/', ' => [$1],', $code);
  134. return $this->indent($code, 1).$checkConditionCode;
  135. }
  136. /**
  137. * Splits static routes from dynamic routes, so that they can be matched first, using a simple switch.
  138. */
  139. private function groupStaticRoutes(RouteCollection $collection): array
  140. {
  141. $staticRoutes = $dynamicRegex = [];
  142. $dynamicRoutes = new RouteCollection();
  143. foreach ($collection->all() as $name => $route) {
  144. $compiledRoute = $route->compile();
  145. $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  146. $hostRegex = $compiledRoute->getHostRegex();
  147. $regex = $compiledRoute->getRegex();
  148. if ($hasTrailingSlash = '/' !== $route->getPath()) {
  149. $pos = strrpos($regex, '$');
  150. $hasTrailingSlash = '/' === $regex[$pos - 1];
  151. $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  152. }
  153. if (!$compiledRoute->getPathVariables()) {
  154. $host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
  155. $url = $route->getPath();
  156. if ($hasTrailingSlash) {
  157. $url = substr($url, 0, -1);
  158. }
  159. foreach ($dynamicRegex as [$hostRx, $rx, $prefix]) {
  160. if (('' === $prefix || 0 === strpos($url, $prefix)) && (preg_match($rx, $url) || preg_match($rx, $url.'/')) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
  161. $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
  162. $dynamicRoutes->add($name, $route);
  163. continue 2;
  164. }
  165. }
  166. $staticRoutes[$url][$name] = [$route, $hasTrailingSlash];
  167. } else {
  168. $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
  169. $dynamicRoutes->add($name, $route);
  170. }
  171. }
  172. return [$staticRoutes, $dynamicRoutes];
  173. }
  174. /**
  175. * Compiles static routes in a switch statement.
  176. *
  177. * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
  178. * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
  179. *
  180. * @throws \LogicException
  181. */
  182. private function compileStaticRoutes(array $staticRoutes, array &$conditions): array
  183. {
  184. if (!$staticRoutes) {
  185. return [];
  186. }
  187. $compiledRoutes = [];
  188. foreach ($staticRoutes as $url => $routes) {
  189. $compiledRoutes[$url] = [];
  190. foreach ($routes as $name => [$route, $hasTrailingSlash]) {
  191. $compiledRoutes[$url][] = $this->compileRoute($route, $name, (!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex()) ?: null, $hasTrailingSlash, false, $conditions);
  192. }
  193. }
  194. return $compiledRoutes;
  195. }
  196. /**
  197. * Compiles a regular expression followed by a switch statement to match dynamic routes.
  198. *
  199. * The regular expression matches both the host and the pathinfo at the same time. For stellar performance,
  200. * it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible.
  201. *
  202. * Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23).
  203. * This name is used to "switch" to the additional logic required to match the final route.
  204. *
  205. * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
  206. * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
  207. *
  208. * Last but not least:
  209. * - Because it is not possible to mix unicode/non-unicode patterns in a single regexp, several of them can be generated.
  210. * - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the
  211. * matching-but-failing subpattern is excluded by replacing its name by "(*F)", which forces a failure-to-match.
  212. * To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur.
  213. */
  214. private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array
  215. {
  216. if (!$collection->all()) {
  217. return [[], [], ''];
  218. }
  219. $regexpList = [];
  220. $code = '';
  221. $state = (object) [
  222. 'regexMark' => 0,
  223. 'regex' => [],
  224. 'routes' => [],
  225. 'mark' => 0,
  226. 'markTail' => 0,
  227. 'hostVars' => [],
  228. 'vars' => [],
  229. ];
  230. $state->getVars = static function ($m) use ($state) {
  231. if ('_route' === $m[1]) {
  232. return '?:';
  233. }
  234. $state->vars[] = $m[1];
  235. return '';
  236. };
  237. $chunkSize = 0;
  238. $prev = null;
  239. $perModifiers = [];
  240. foreach ($collection->all() as $name => $route) {
  241. preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
  242. if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {
  243. $chunkSize = 1;
  244. $routes = new RouteCollection();
  245. $perModifiers[] = [$rx[0], $routes];
  246. $prev = $rx[0];
  247. }
  248. $routes->add($name, $route);
  249. }
  250. foreach ($perModifiers as [$modifiers, $routes]) {
  251. $prev = false;
  252. $perHost = [];
  253. foreach ($routes->all() as $name => $route) {
  254. $regex = $route->compile()->getHostRegex();
  255. if ($prev !== $regex) {
  256. $routes = new RouteCollection();
  257. $perHost[] = [$regex, $routes];
  258. $prev = $regex;
  259. }
  260. $routes->add($name, $route);
  261. }
  262. $prev = false;
  263. $rx = '{^(?';
  264. $code .= "\n {$state->mark} => ".self::export($rx);
  265. $startingMark = $state->mark;
  266. $state->mark += \strlen($rx);
  267. $state->regex = $rx;
  268. foreach ($perHost as [$hostRegex, $routes]) {
  269. if ($matchHost) {
  270. if ($hostRegex) {
  271. preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx);
  272. $state->vars = [];
  273. $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.';
  274. $state->hostVars = $state->vars;
  275. } else {
  276. $hostRegex = '(?:(?:[^./]*+\.)++)';
  277. $state->hostVars = [];
  278. }
  279. $state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?");
  280. $code .= "\n .".self::export($rx);
  281. $state->regex .= $rx;
  282. $prev = true;
  283. }
  284. $tree = new StaticPrefixCollection();
  285. foreach ($routes->all() as $name => $route) {
  286. preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
  287. $state->vars = [];
  288. $regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
  289. if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
  290. $regex = substr($regex, 0, -1);
  291. }
  292. $hasTrailingVar = (bool) preg_match('#\{\w+\}/?$#', $route->getPath());
  293. $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]);
  294. }
  295. $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);
  296. }
  297. if ($matchHost) {
  298. $code .= "\n .')'";
  299. $state->regex .= ')';
  300. }
  301. $rx = ")/?$}{$modifiers}";
  302. $code .= "\n .'{$rx}',";
  303. $state->regex .= $rx;
  304. $state->markTail = 0;
  305. // if the regex is too large, throw a signaling exception to recompute with smaller chunk size
  306. set_error_handler(function ($type, $message) { throw false !== strpos($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); });
  307. try {
  308. preg_match($state->regex, '');
  309. } finally {
  310. restore_error_handler();
  311. }
  312. $regexpList[$startingMark] = $state->regex;
  313. }
  314. $state->routes[$state->mark][] = [null, null, null, null, false, false, 0];
  315. unset($state->getVars);
  316. return [$regexpList, $state->routes, $code];
  317. }
  318. /**
  319. * Compiles a regexp tree of subpatterns that matches nested same-prefix routes.
  320. *
  321. * @param \stdClass $state A simple state object that keeps track of the progress of the compilation,
  322. * and gathers the generated switch's "case" and "default" statements
  323. */
  324. private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string
  325. {
  326. $code = '';
  327. $prevRegex = null;
  328. $routes = $tree->getRoutes();
  329. foreach ($routes as $i => $route) {
  330. if ($route instanceof StaticPrefixCollection) {
  331. $prevRegex = null;
  332. $prefix = substr($route->getPrefix(), $prefixLen);
  333. $state->mark += \strlen($rx = "|{$prefix}(?");
  334. $code .= "\n .".self::export($rx);
  335. $state->regex .= $rx;
  336. $code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions));
  337. $code .= "\n .')'";
  338. $state->regex .= ')';
  339. ++$state->markTail;
  340. continue;
  341. }
  342. [$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route;
  343. $compiledRoute = $route->compile();
  344. $vars = array_merge($state->hostVars, $vars);
  345. if ($compiledRoute->getRegex() === $prevRegex) {
  346. $state->routes[$state->mark][] = $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions);
  347. continue;
  348. }
  349. $state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen;
  350. $state->markTail = 2 + \strlen($state->mark);
  351. $rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark);
  352. $code .= "\n .".self::export($rx);
  353. $state->regex .= $rx;
  354. $prevRegex = $compiledRoute->getRegex();
  355. $state->routes[$state->mark] = [$this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions)];
  356. }
  357. return $code;
  358. }
  359. /**
  360. * Compiles a single Route to PHP code used to match it against the path info.
  361. */
  362. private function compileRoute(Route $route, string $name, $vars, bool $hasTrailingSlash, bool $hasTrailingVar, array &$conditions): array
  363. {
  364. $defaults = $route->getDefaults();
  365. if (isset($defaults['_canonical_route'])) {
  366. $name = $defaults['_canonical_route'];
  367. unset($defaults['_canonical_route']);
  368. }
  369. if ($condition = $route->getCondition()) {
  370. $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']);
  371. $condition = $conditions[$condition] ?? $conditions[$condition] = (false !== strpos($condition, '$request') ? 1 : -1) * \count($conditions);
  372. } else {
  373. $condition = null;
  374. }
  375. return [
  376. ['_route' => $name] + $defaults,
  377. $vars,
  378. array_flip($route->getMethods()) ?: null,
  379. array_flip($route->getSchemes()) ?: null,
  380. $hasTrailingSlash,
  381. $hasTrailingVar,
  382. $condition,
  383. ];
  384. }
  385. private function getExpressionLanguage(): ExpressionLanguage
  386. {
  387. if (null === $this->expressionLanguage) {
  388. if (!class_exists(ExpressionLanguage::class)) {
  389. throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  390. }
  391. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  392. }
  393. return $this->expressionLanguage;
  394. }
  395. private function indent(string $code, int $level = 1): string
  396. {
  397. return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code);
  398. }
  399. /**
  400. * @internal
  401. */
  402. public static function export($value): string
  403. {
  404. if (null === $value) {
  405. return 'null';
  406. }
  407. if (!\is_array($value)) {
  408. if (\is_object($value)) {
  409. throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.');
  410. }
  411. return str_replace("\n", '\'."\n".\'', var_export($value, true));
  412. }
  413. if (!$value) {
  414. return '[]';
  415. }
  416. $i = 0;
  417. $export = '[';
  418. foreach ($value as $k => $v) {
  419. if ($i === $k) {
  420. ++$i;
  421. } else {
  422. $export .= self::export($k).' => ';
  423. if (\is_int($k) && $i < $k) {
  424. $i = 1 + $k;
  425. }
  426. }
  427. $export .= self::export($v).', ';
  428. }
  429. return substr_replace($export, ']', -2);
  430. }
  431. }