PhpMatcherDumper.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. * PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
  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. */
  22. class PhpMatcherDumper extends MatcherDumper
  23. {
  24. private $expressionLanguage;
  25. /**
  26. * @var ExpressionFunctionProviderInterface[]
  27. */
  28. private $expressionLanguageProviders = [];
  29. /**
  30. * Dumps a set of routes to a PHP class.
  31. *
  32. * Available options:
  33. *
  34. * * class: The class name
  35. * * base_class: The base class name
  36. *
  37. * @param array $options An array of options
  38. *
  39. * @return string A PHP class representing the matcher class
  40. */
  41. public function dump(array $options = [])
  42. {
  43. $options = array_replace([
  44. 'class' => 'ProjectUrlMatcher',
  45. 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  46. ], $options);
  47. // trailing slash support is only enabled if we know how to redirect the user
  48. $interfaces = class_implements($options['base_class']);
  49. $supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
  50. return <<<EOF
  51. <?php
  52. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  53. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  54. use Symfony\Component\Routing\RequestContext;
  55. /**
  56. * This class has been auto-generated
  57. * by the Symfony Routing Component.
  58. */
  59. class {$options['class']} extends {$options['base_class']}
  60. {
  61. public function __construct(RequestContext \$context)
  62. {
  63. \$this->context = \$context;
  64. }
  65. {$this->generateMatchMethod($supportsRedirections)}
  66. }
  67. EOF;
  68. }
  69. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  70. {
  71. $this->expressionLanguageProviders[] = $provider;
  72. }
  73. /**
  74. * Generates the code for the match method implementing UrlMatcherInterface.
  75. *
  76. * @param bool $supportsRedirections Whether redirections are supported by the base class
  77. *
  78. * @return string Match method as PHP code
  79. */
  80. private function generateMatchMethod($supportsRedirections)
  81. {
  82. $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
  83. return <<<EOF
  84. public function match(\$rawPathinfo)
  85. {
  86. \$allow = [];
  87. \$pathinfo = rawurldecode(\$rawPathinfo);
  88. \$trimmedPathinfo = rtrim(\$pathinfo, '/');
  89. \$context = \$this->context;
  90. \$request = \$this->request ?: \$this->createRequest(\$pathinfo);
  91. \$requestMethod = \$canonicalMethod = \$context->getMethod();
  92. if ('HEAD' === \$requestMethod) {
  93. \$canonicalMethod = 'GET';
  94. }
  95. $code
  96. throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
  97. }
  98. EOF;
  99. }
  100. /**
  101. * Generates PHP code to match a RouteCollection with all its routes.
  102. *
  103. * @param RouteCollection $routes A RouteCollection instance
  104. * @param bool $supportsRedirections Whether redirections are supported by the base class
  105. *
  106. * @return string PHP code
  107. */
  108. private function compileRoutes(RouteCollection $routes, $supportsRedirections)
  109. {
  110. $fetchedHost = false;
  111. $groups = $this->groupRoutesByHostRegex($routes);
  112. $code = '';
  113. foreach ($groups as $collection) {
  114. if (null !== $regex = $collection->getAttribute('host_regex')) {
  115. if (!$fetchedHost) {
  116. $code .= " \$host = \$context->getHost();\n\n";
  117. $fetchedHost = true;
  118. }
  119. $code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
  120. }
  121. $tree = $this->buildStaticPrefixCollection($collection);
  122. $groupCode = $this->compileStaticPrefixRoutes($tree, $supportsRedirections);
  123. if (null !== $regex) {
  124. // apply extra indention at each line (except empty ones)
  125. $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
  126. $code .= $groupCode;
  127. $code .= " }\n\n";
  128. } else {
  129. $code .= $groupCode;
  130. }
  131. }
  132. // used to display the Welcome Page in apps that don't define a homepage
  133. $code .= " if ('/' === \$pathinfo && !\$allow) {\n";
  134. $code .= " throw new Symfony\Component\Routing\Exception\NoConfigurationException();\n";
  135. $code .= " }\n";
  136. return $code;
  137. }
  138. private function buildStaticPrefixCollection(DumperCollection $collection)
  139. {
  140. $prefixCollection = new StaticPrefixCollection();
  141. foreach ($collection as $dumperRoute) {
  142. $prefix = $dumperRoute->getRoute()->compile()->getStaticPrefix();
  143. $prefixCollection->addRoute($prefix, $dumperRoute);
  144. }
  145. $prefixCollection->optimizeGroups();
  146. return $prefixCollection;
  147. }
  148. /**
  149. * Generates PHP code to match a tree of routes.
  150. *
  151. * @param StaticPrefixCollection $collection A StaticPrefixCollection instance
  152. * @param bool $supportsRedirections Whether redirections are supported by the base class
  153. * @param string $ifOrElseIf either "if" or "elseif" to influence chaining
  154. *
  155. * @return string PHP code
  156. */
  157. private function compileStaticPrefixRoutes(StaticPrefixCollection $collection, $supportsRedirections, $ifOrElseIf = 'if')
  158. {
  159. $code = '';
  160. $prefix = $collection->getPrefix();
  161. if (!empty($prefix) && '/' !== $prefix) {
  162. $code .= sprintf(" %s (0 === strpos(\$pathinfo, %s)) {\n", $ifOrElseIf, var_export($prefix, true));
  163. }
  164. $ifOrElseIf = 'if';
  165. foreach ($collection->getItems() as $route) {
  166. if ($route instanceof StaticPrefixCollection) {
  167. $code .= $this->compileStaticPrefixRoutes($route, $supportsRedirections, $ifOrElseIf);
  168. $ifOrElseIf = 'elseif';
  169. } else {
  170. $code .= $this->compileRoute($route[1]->getRoute(), $route[1]->getName(), $supportsRedirections, $prefix)."\n";
  171. $ifOrElseIf = 'if';
  172. }
  173. }
  174. if (!empty($prefix) && '/' !== $prefix) {
  175. $code .= " }\n\n";
  176. // apply extra indention at each line (except empty ones)
  177. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  178. }
  179. return $code;
  180. }
  181. /**
  182. * Compiles a single Route to PHP code used to match it against the path info.
  183. *
  184. * @param Route $route A Route instance
  185. * @param string $name The name of the Route
  186. * @param bool $supportsRedirections Whether redirections are supported by the base class
  187. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  188. *
  189. * @return string PHP code
  190. *
  191. * @throws \LogicException
  192. */
  193. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  194. {
  195. $code = '';
  196. $compiledRoute = $route->compile();
  197. $conditions = [];
  198. $hasTrailingSlash = false;
  199. $matches = false;
  200. $hostMatches = false;
  201. $methods = $route->getMethods();
  202. $supportsTrailingSlash = $supportsRedirections && (!$methods || \in_array('GET', $methods));
  203. $regex = $compiledRoute->getRegex();
  204. if (!\count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#'.('u' === substr($regex, -1) ? 'u' : ''), $regex, $m)) {
  205. if ($supportsTrailingSlash && '/' === substr($m['url'], -1)) {
  206. $conditions[] = sprintf('%s === $trimmedPathinfo', var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  207. $hasTrailingSlash = true;
  208. } else {
  209. $conditions[] = sprintf('%s === $pathinfo', var_export(str_replace('\\', '', $m['url']), true));
  210. }
  211. } else {
  212. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  213. $conditions[] = sprintf('0 === strpos($pathinfo, %s)', var_export($compiledRoute->getStaticPrefix(), true));
  214. }
  215. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  216. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  217. $hasTrailingSlash = true;
  218. }
  219. $conditions[] = sprintf('preg_match(%s, $pathinfo, $matches)', var_export($regex, true));
  220. $matches = true;
  221. }
  222. if ($compiledRoute->getHostVariables()) {
  223. $hostMatches = true;
  224. }
  225. if ($route->getCondition()) {
  226. $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), ['context', 'request']);
  227. }
  228. $conditions = implode(' && ', $conditions);
  229. $code .= <<<EOF
  230. // $name
  231. if ($conditions) {
  232. EOF;
  233. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  234. // the offset where the return value is appended below, with indendation
  235. $retOffset = 12 + \strlen($code);
  236. // optimize parameters array
  237. if ($matches || $hostMatches) {
  238. $vars = [];
  239. if ($hostMatches) {
  240. $vars[] = '$hostMatches';
  241. }
  242. if ($matches) {
  243. $vars[] = '$matches';
  244. }
  245. $vars[] = "['_route' => '$name']";
  246. $code .= sprintf(
  247. " \$ret = \$this->mergeDefaults(array_replace(%s), %s);\n",
  248. implode(', ', $vars),
  249. str_replace("\n", '', var_export($route->getDefaults(), true))
  250. );
  251. } elseif ($route->getDefaults()) {
  252. $code .= sprintf(" \$ret = %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), ['_route' => $name]), true)));
  253. } else {
  254. $code .= sprintf(" \$ret = ['_route' => '%s'];\n", $name);
  255. }
  256. if ($hasTrailingSlash) {
  257. $code .= <<<EOF
  258. if ('/' === substr(\$pathinfo, -1)) {
  259. // no-op
  260. } elseif ('GET' !== \$canonicalMethod) {
  261. goto $gotoname;
  262. } else {
  263. return array_replace(\$ret, \$this->redirect(\$rawPathinfo.'/', '$name'));
  264. }
  265. EOF;
  266. }
  267. if ($methods) {
  268. $methodVariable = \in_array('GET', $methods) ? '$canonicalMethod' : '$requestMethod';
  269. $methods = implode("', '", $methods);
  270. }
  271. if ($schemes = $route->getSchemes()) {
  272. if (!$supportsRedirections) {
  273. throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  274. }
  275. $schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
  276. if ($methods) {
  277. $code .= <<<EOF
  278. \$requiredSchemes = $schemes;
  279. \$hasRequiredScheme = isset(\$requiredSchemes[\$context->getScheme()]);
  280. if (!in_array($methodVariable, ['$methods'])) {
  281. if (\$hasRequiredScheme) {
  282. \$allow = array_merge(\$allow, ['$methods']);
  283. }
  284. goto $gotoname;
  285. }
  286. if (!\$hasRequiredScheme) {
  287. if ('GET' !== \$canonicalMethod) {
  288. goto $gotoname;
  289. }
  290. return array_replace(\$ret, \$this->redirect(\$rawPathinfo, '$name', key(\$requiredSchemes)));
  291. }
  292. EOF;
  293. } else {
  294. $code .= <<<EOF
  295. \$requiredSchemes = $schemes;
  296. if (!isset(\$requiredSchemes[\$context->getScheme()])) {
  297. if ('GET' !== \$canonicalMethod) {
  298. goto $gotoname;
  299. }
  300. return array_replace(\$ret, \$this->redirect(\$rawPathinfo, '$name', key(\$requiredSchemes)));
  301. }
  302. EOF;
  303. }
  304. } elseif ($methods) {
  305. $code .= <<<EOF
  306. if (!in_array($methodVariable, ['$methods'])) {
  307. \$allow = array_merge(\$allow, ['$methods']);
  308. goto $gotoname;
  309. }
  310. EOF;
  311. }
  312. if ($hasTrailingSlash || $schemes || $methods) {
  313. $code .= " return \$ret;\n";
  314. } else {
  315. $code = substr_replace($code, 'return', $retOffset, 6);
  316. }
  317. $code .= " }\n";
  318. if ($hasTrailingSlash || $schemes || $methods) {
  319. $code .= " $gotoname:\n";
  320. }
  321. return $code;
  322. }
  323. /**
  324. * Groups consecutive routes having the same host regex.
  325. *
  326. * The result is a collection of collections of routes having the same host regex.
  327. *
  328. * @param RouteCollection $routes A flat RouteCollection
  329. *
  330. * @return DumperCollection A collection with routes grouped by host regex in sub-collections
  331. */
  332. private function groupRoutesByHostRegex(RouteCollection $routes)
  333. {
  334. $groups = new DumperCollection();
  335. $currentGroup = new DumperCollection();
  336. $currentGroup->setAttribute('host_regex', null);
  337. $groups->add($currentGroup);
  338. foreach ($routes as $name => $route) {
  339. $hostRegex = $route->compile()->getHostRegex();
  340. if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
  341. $currentGroup = new DumperCollection();
  342. $currentGroup->setAttribute('host_regex', $hostRegex);
  343. $groups->add($currentGroup);
  344. }
  345. $currentGroup->add(new DumperRoute($name, $route));
  346. }
  347. return $groups;
  348. }
  349. private function getExpressionLanguage()
  350. {
  351. if (null === $this->expressionLanguage) {
  352. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  353. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  354. }
  355. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  356. }
  357. return $this->expressionLanguage;
  358. }
  359. }