CompiledUrlMatcherDumper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. $r = array_map([__CLASS__, 'export'], $route);
  119. $code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", $r[0], $r[1], $r[2], $r[3], $r[4], $r[5], $r[6]);
  120. }
  121. $code .= " ],\n";
  122. }
  123. $code .= "],\n";
  124. $code .= sprintf("[ // \$regexpList%s\n],\n", $regexpCode);
  125. $code .= '[ // $dynamicRoutes'."\n";
  126. foreach ($dynamicRoutes as $path => $routes) {
  127. $code .= sprintf(" %s => [\n", self::export($path));
  128. foreach ($routes as $route) {
  129. $r = array_map([__CLASS__, 'export'], $route);
  130. $code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", $r[0], $r[1], $r[2], $r[3], $r[4], $r[5], $r[6]);
  131. }
  132. $code .= " ],\n";
  133. }
  134. $code .= "],\n";
  135. $code = preg_replace('/ => \[\n (\[.+?),\n \],/', ' => [$1],', $code);
  136. return $this->indent($code, 1).$checkConditionCode;
  137. }
  138. /**
  139. * Splits static routes from dynamic routes, so that they can be matched first, using a simple switch.
  140. */
  141. private function groupStaticRoutes(RouteCollection $collection): array
  142. {
  143. $staticRoutes = $dynamicRegex = [];
  144. $dynamicRoutes = new RouteCollection();
  145. foreach ($collection->all() as $name => $route) {
  146. $compiledRoute = $route->compile();
  147. $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  148. $hostRegex = $compiledRoute->getHostRegex();
  149. $regex = $compiledRoute->getRegex();
  150. if ($hasTrailingSlash = '/' !== $route->getPath()) {
  151. $pos = strrpos($regex, '$');
  152. $hasTrailingSlash = '/' === $regex[$pos - 1];
  153. $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  154. }
  155. if (!$compiledRoute->getPathVariables()) {
  156. $host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
  157. $url = $route->getPath();
  158. if ($hasTrailingSlash) {
  159. $url = substr($url, 0, -1);
  160. }
  161. foreach ($dynamicRegex as [$hostRx, $rx, $prefix]) {
  162. if (('' === $prefix || str_starts_with($url, $prefix)) && (preg_match($rx, $url) || preg_match($rx, $url.'/')) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
  163. $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
  164. $dynamicRoutes->add($name, $route);
  165. continue 2;
  166. }
  167. }
  168. $staticRoutes[$url][$name] = [$route, $hasTrailingSlash];
  169. } else {
  170. $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
  171. $dynamicRoutes->add($name, $route);
  172. }
  173. }
  174. return [$staticRoutes, $dynamicRoutes];
  175. }
  176. /**
  177. * Compiles static routes in a switch statement.
  178. *
  179. * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
  180. * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
  181. *
  182. * @throws \LogicException
  183. */
  184. private function compileStaticRoutes(array $staticRoutes, array &$conditions): array
  185. {
  186. if (!$staticRoutes) {
  187. return [];
  188. }
  189. $compiledRoutes = [];
  190. foreach ($staticRoutes as $url => $routes) {
  191. $compiledRoutes[$url] = [];
  192. foreach ($routes as $name => [$route, $hasTrailingSlash]) {
  193. $compiledRoutes[$url][] = $this->compileRoute($route, $name, (!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex()) ?: null, $hasTrailingSlash, false, $conditions);
  194. }
  195. }
  196. return $compiledRoutes;
  197. }
  198. /**
  199. * Compiles a regular expression followed by a switch statement to match dynamic routes.
  200. *
  201. * The regular expression matches both the host and the pathinfo at the same time. For stellar performance,
  202. * it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible.
  203. *
  204. * Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23).
  205. * This name is used to "switch" to the additional logic required to match the final route.
  206. *
  207. * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
  208. * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
  209. *
  210. * Last but not least:
  211. * - Because it is not possible to mix unicode/non-unicode patterns in a single regexp, several of them can be generated.
  212. * - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the
  213. * matching-but-failing subpattern is excluded by replacing its name by "(*F)", which forces a failure-to-match.
  214. * To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur.
  215. */
  216. private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array
  217. {
  218. if (!$collection->all()) {
  219. return [[], [], ''];
  220. }
  221. $regexpList = [];
  222. $code = '';
  223. $state = (object) [
  224. 'regexMark' => 0,
  225. 'regex' => [],
  226. 'routes' => [],
  227. 'mark' => 0,
  228. 'markTail' => 0,
  229. 'hostVars' => [],
  230. 'vars' => [],
  231. ];
  232. $state->getVars = static function ($m) use ($state) {
  233. if ('_route' === $m[1]) {
  234. return '?:';
  235. }
  236. $state->vars[] = $m[1];
  237. return '';
  238. };
  239. $chunkSize = 0;
  240. $prev = null;
  241. $perModifiers = [];
  242. foreach ($collection->all() as $name => $route) {
  243. preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
  244. if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {
  245. $chunkSize = 1;
  246. $routes = new RouteCollection();
  247. $perModifiers[] = [$rx[0], $routes];
  248. $prev = $rx[0];
  249. }
  250. $routes->add($name, $route);
  251. }
  252. foreach ($perModifiers as [$modifiers, $routes]) {
  253. $prev = false;
  254. $perHost = [];
  255. foreach ($routes->all() as $name => $route) {
  256. $regex = $route->compile()->getHostRegex();
  257. if ($prev !== $regex) {
  258. $routes = new RouteCollection();
  259. $perHost[] = [$regex, $routes];
  260. $prev = $regex;
  261. }
  262. $routes->add($name, $route);
  263. }
  264. $prev = false;
  265. $rx = '{^(?';
  266. $code .= "\n {$state->mark} => ".self::export($rx);
  267. $startingMark = $state->mark;
  268. $state->mark += \strlen($rx);
  269. $state->regex = $rx;
  270. foreach ($perHost as [$hostRegex, $routes]) {
  271. if ($matchHost) {
  272. if ($hostRegex) {
  273. preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx);
  274. $state->vars = [];
  275. $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.';
  276. $state->hostVars = $state->vars;
  277. } else {
  278. $hostRegex = '(?:(?:[^./]*+\.)++)';
  279. $state->hostVars = [];
  280. }
  281. $state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?");
  282. $code .= "\n .".self::export($rx);
  283. $state->regex .= $rx;
  284. $prev = true;
  285. }
  286. $tree = new StaticPrefixCollection();
  287. foreach ($routes->all() as $name => $route) {
  288. preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
  289. $state->vars = [];
  290. $regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
  291. if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
  292. $regex = substr($regex, 0, -1);
  293. }
  294. $hasTrailingVar = (bool) preg_match('#\{\w+\}/?$#', $route->getPath());
  295. $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]);
  296. }
  297. $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);
  298. }
  299. if ($matchHost) {
  300. $code .= "\n .')'";
  301. $state->regex .= ')';
  302. }
  303. $rx = ")/?$}{$modifiers}";
  304. $code .= "\n .'{$rx}',";
  305. $state->regex .= $rx;
  306. $state->markTail = 0;
  307. // if the regex is too large, throw a signaling exception to recompute with smaller chunk size
  308. set_error_handler(function ($type, $message) { throw str_contains($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); });
  309. try {
  310. preg_match($state->regex, '');
  311. } finally {
  312. restore_error_handler();
  313. }
  314. $regexpList[$startingMark] = $state->regex;
  315. }
  316. $state->routes[$state->mark][] = [null, null, null, null, false, false, 0];
  317. unset($state->getVars);
  318. return [$regexpList, $state->routes, $code];
  319. }
  320. /**
  321. * Compiles a regexp tree of subpatterns that matches nested same-prefix routes.
  322. *
  323. * @param \stdClass $state A simple state object that keeps track of the progress of the compilation,
  324. * and gathers the generated switch's "case" and "default" statements
  325. */
  326. private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string
  327. {
  328. $code = '';
  329. $prevRegex = null;
  330. $routes = $tree->getRoutes();
  331. foreach ($routes as $i => $route) {
  332. if ($route instanceof StaticPrefixCollection) {
  333. $prevRegex = null;
  334. $prefix = substr($route->getPrefix(), $prefixLen);
  335. $state->mark += \strlen($rx = "|{$prefix}(?");
  336. $code .= "\n .".self::export($rx);
  337. $state->regex .= $rx;
  338. $code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions));
  339. $code .= "\n .')'";
  340. $state->regex .= ')';
  341. ++$state->markTail;
  342. continue;
  343. }
  344. [$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route;
  345. $compiledRoute = $route->compile();
  346. $vars = array_merge($state->hostVars, $vars);
  347. if ($compiledRoute->getRegex() === $prevRegex) {
  348. $state->routes[$state->mark][] = $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions);
  349. continue;
  350. }
  351. $state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen;
  352. $state->markTail = 2 + \strlen($state->mark);
  353. $rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark);
  354. $code .= "\n .".self::export($rx);
  355. $state->regex .= $rx;
  356. $prevRegex = $compiledRoute->getRegex();
  357. $state->routes[$state->mark] = [$this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions)];
  358. }
  359. return $code;
  360. }
  361. /**
  362. * Compiles a single Route to PHP code used to match it against the path info.
  363. */
  364. private function compileRoute(Route $route, string $name, $vars, bool $hasTrailingSlash, bool $hasTrailingVar, array &$conditions): array
  365. {
  366. $defaults = $route->getDefaults();
  367. if (isset($defaults['_canonical_route'])) {
  368. $name = $defaults['_canonical_route'];
  369. unset($defaults['_canonical_route']);
  370. }
  371. if ($condition = $route->getCondition()) {
  372. $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']);
  373. $condition = $conditions[$condition] ?? $conditions[$condition] = (str_contains($condition, '$request') ? 1 : -1) * \count($conditions);
  374. } else {
  375. $condition = null;
  376. }
  377. return [
  378. ['_route' => $name] + $defaults,
  379. $vars,
  380. array_flip($route->getMethods()) ?: null,
  381. array_flip($route->getSchemes()) ?: null,
  382. $hasTrailingSlash,
  383. $hasTrailingVar,
  384. $condition,
  385. ];
  386. }
  387. private function getExpressionLanguage(): ExpressionLanguage
  388. {
  389. if (null === $this->expressionLanguage) {
  390. if (!class_exists(ExpressionLanguage::class)) {
  391. throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  392. }
  393. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  394. }
  395. return $this->expressionLanguage;
  396. }
  397. private function indent(string $code, int $level = 1): string
  398. {
  399. return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code);
  400. }
  401. /**
  402. * @internal
  403. */
  404. public static function export($value): string
  405. {
  406. if (null === $value) {
  407. return 'null';
  408. }
  409. if (!\is_array($value)) {
  410. if (\is_object($value)) {
  411. throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.');
  412. }
  413. return str_replace("\n", '\'."\n".\'', var_export($value, true));
  414. }
  415. if (!$value) {
  416. return '[]';
  417. }
  418. $i = 0;
  419. $export = '[';
  420. foreach ($value as $k => $v) {
  421. if ($i === $k) {
  422. ++$i;
  423. } else {
  424. $export .= self::export($k).' => ';
  425. if (\is_int($k) && $i < $k) {
  426. $i = 1 + $k;
  427. }
  428. }
  429. $export .= self::export($v).', ';
  430. }
  431. return substr_replace($export, ']', -2);
  432. }
  433. }