PhpMatcherDumper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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\Routing\Route;
  12. use Symfony\Component\Routing\RouteCollection;
  13. /**
  14. * PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Tobias Schultze <http://tobion.de>
  18. * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
  19. */
  20. class PhpMatcherDumper extends MatcherDumper
  21. {
  22. /**
  23. * Dumps a set of routes to a PHP class.
  24. *
  25. * Available options:
  26. *
  27. * * class: The class name
  28. * * base_class: The base class name
  29. *
  30. * @param array $options An array of options
  31. *
  32. * @return string A PHP class representing the matcher class
  33. */
  34. public function dump(array $options = array())
  35. {
  36. $options = array_replace(array(
  37. 'class' => 'ProjectUrlMatcher',
  38. 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  39. ), $options);
  40. // trailing slash support is only enabled if we know how to redirect the user
  41. $interfaces = class_implements($options['base_class']);
  42. $supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
  43. return <<<EOF
  44. <?php
  45. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  46. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  47. use Symfony\Component\Routing\RequestContext;
  48. /**
  49. * {$options['class']}
  50. *
  51. * This class has been auto-generated
  52. * by the Symfony Routing Component.
  53. */
  54. class {$options['class']} extends {$options['base_class']}
  55. {
  56. /**
  57. * Constructor.
  58. */
  59. public function __construct(RequestContext \$context)
  60. {
  61. \$this->context = \$context;
  62. }
  63. {$this->generateMatchMethod($supportsRedirections)}
  64. }
  65. EOF;
  66. }
  67. /**
  68. * Generates the code for the match method implementing UrlMatcherInterface.
  69. *
  70. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  71. *
  72. * @return string Match method as PHP code
  73. */
  74. private function generateMatchMethod($supportsRedirections)
  75. {
  76. $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
  77. return <<<EOF
  78. public function match(\$pathinfo)
  79. {
  80. \$allow = array();
  81. \$pathinfo = rawurldecode(\$pathinfo);
  82. $code
  83. throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
  84. }
  85. EOF;
  86. }
  87. /**
  88. * Generates PHP code to match a RouteCollection with all its routes.
  89. *
  90. * @param RouteCollection $routes A RouteCollection instance
  91. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  92. *
  93. * @return string PHP code
  94. */
  95. private function compileRoutes(RouteCollection $routes, $supportsRedirections)
  96. {
  97. $fetchedHost = false;
  98. $groups = $this->groupRoutesByHostRegex($routes);
  99. $code = '';
  100. foreach ($groups as $collection) {
  101. if (null !== $regex = $collection->getAttribute('host_regex')) {
  102. if (!$fetchedHost) {
  103. $code .= " \$host = \$this->context->getHost();\n\n";
  104. $fetchedHost = true;
  105. }
  106. $code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
  107. }
  108. $tree = $this->buildPrefixTree($collection);
  109. $groupCode = $this->compilePrefixRoutes($tree, $supportsRedirections);
  110. if (null !== $regex) {
  111. // apply extra indention at each line (except empty ones)
  112. $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
  113. $code .= $groupCode;
  114. $code .= " }\n\n";
  115. } else {
  116. $code .= $groupCode;
  117. }
  118. }
  119. return $code;
  120. }
  121. /**
  122. * Generates PHP code recursively to match a tree of routes
  123. *
  124. * @param DumperPrefixCollection $collection A DumperPrefixCollection instance
  125. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  126. * @param string $parentPrefix Prefix of the parent collection
  127. *
  128. * @return string PHP code
  129. */
  130. private function compilePrefixRoutes(DumperPrefixCollection $collection, $supportsRedirections, $parentPrefix = '')
  131. {
  132. $code = '';
  133. $prefix = $collection->getPrefix();
  134. $optimizable = 1 < strlen($prefix) && 1 < count($collection->all());
  135. $optimizedPrefix = $parentPrefix;
  136. if ($optimizable) {
  137. $optimizedPrefix = $prefix;
  138. $code .= sprintf(" if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));
  139. }
  140. foreach ($collection as $route) {
  141. if ($route instanceof DumperCollection) {
  142. $code .= $this->compilePrefixRoutes($route, $supportsRedirections, $optimizedPrefix);
  143. } else {
  144. $code .= $this->compileRoute($route->getRoute(), $route->getName(), $supportsRedirections, $optimizedPrefix)."\n";
  145. }
  146. }
  147. if ($optimizable) {
  148. $code .= " }\n\n";
  149. // apply extra indention at each line (except empty ones)
  150. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  151. }
  152. return $code;
  153. }
  154. /**
  155. * Compiles a single Route to PHP code used to match it against the path info.
  156. *
  157. * @param Route $route A Route instance
  158. * @param string $name The name of the Route
  159. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  160. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  161. *
  162. * @return string PHP code
  163. *
  164. * @throws \LogicException
  165. */
  166. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  167. {
  168. $code = '';
  169. $compiledRoute = $route->compile();
  170. $conditions = array();
  171. $hasTrailingSlash = false;
  172. $matches = false;
  173. $hostMatches = false;
  174. $methods = array();
  175. if ($req = $route->getRequirement('_method')) {
  176. $methods = explode('|', strtoupper($req));
  177. // GET and HEAD are equivalent
  178. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  179. $methods[] = 'HEAD';
  180. }
  181. }
  182. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
  183. if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
  184. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  185. $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  186. $hasTrailingSlash = true;
  187. } else {
  188. $conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
  189. }
  190. } else {
  191. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  192. $conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
  193. }
  194. $regex = $compiledRoute->getRegex();
  195. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  196. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  197. $hasTrailingSlash = true;
  198. }
  199. $conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));
  200. $matches = true;
  201. }
  202. if ($compiledRoute->getHostVariables()) {
  203. $hostMatches = true;
  204. }
  205. $conditions = implode(' && ', $conditions);
  206. $code .= <<<EOF
  207. // $name
  208. if ($conditions) {
  209. EOF;
  210. if ($methods) {
  211. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  212. if (1 === count($methods)) {
  213. $code .= <<<EOF
  214. if (\$this->context->getMethod() != '$methods[0]') {
  215. \$allow[] = '$methods[0]';
  216. goto $gotoname;
  217. }
  218. EOF;
  219. } else {
  220. $methods = implode("', '", $methods);
  221. $code .= <<<EOF
  222. if (!in_array(\$this->context->getMethod(), array('$methods'))) {
  223. \$allow = array_merge(\$allow, array('$methods'));
  224. goto $gotoname;
  225. }
  226. EOF;
  227. }
  228. }
  229. if ($hasTrailingSlash) {
  230. $code .= <<<EOF
  231. if (substr(\$pathinfo, -1) !== '/') {
  232. return \$this->redirect(\$pathinfo.'/', '$name');
  233. }
  234. EOF;
  235. }
  236. if ($scheme = $route->getRequirement('_scheme')) {
  237. if (!$supportsRedirections) {
  238. throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  239. }
  240. $code .= <<<EOF
  241. if (\$this->context->getScheme() !== '$scheme') {
  242. return \$this->redirect(\$pathinfo, '$name', '$scheme');
  243. }
  244. EOF;
  245. }
  246. // optimize parameters array
  247. if ($matches || $hostMatches) {
  248. $vars = array();
  249. if ($hostMatches) {
  250. $vars[] = '$hostMatches';
  251. }
  252. if ($matches) {
  253. $vars[] = '$matches';
  254. }
  255. $vars[] = "array('_route' => '$name')";
  256. $code .= sprintf(" return \$this->mergeDefaults(array_replace(%s), %s);\n"
  257. , implode(', ', $vars), str_replace("\n", '', var_export($route->getDefaults(), true)));
  258. } elseif ($route->getDefaults()) {
  259. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
  260. } else {
  261. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  262. }
  263. $code .= " }\n";
  264. if ($methods) {
  265. $code .= " $gotoname:\n";
  266. }
  267. return $code;
  268. }
  269. /**
  270. * Groups consecutive routes having the same host regex.
  271. *
  272. * The result is a collection of collections of routes having the same host regex.
  273. *
  274. * @param RouteCollection $routes A flat RouteCollection
  275. *
  276. * @return DumperCollection A collection with routes grouped by host regex in sub-collections
  277. */
  278. private function groupRoutesByHostRegex(RouteCollection $routes)
  279. {
  280. $groups = new DumperCollection();
  281. $currentGroup = new DumperCollection();
  282. $currentGroup->setAttribute('host_regex', null);
  283. $groups->add($currentGroup);
  284. foreach ($routes as $name => $route) {
  285. $hostRegex = $route->compile()->getHostRegex();
  286. if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
  287. $currentGroup = new DumperCollection();
  288. $currentGroup->setAttribute('host_regex', $hostRegex);
  289. $groups->add($currentGroup);
  290. }
  291. $currentGroup->add(new DumperRoute($name, $route));
  292. }
  293. return $groups;
  294. }
  295. /**
  296. * Organizes the routes into a prefix tree.
  297. *
  298. * Routes order is preserved such that traversing the tree will traverse the
  299. * routes in the origin order.
  300. *
  301. * @param DumperCollection $collection A collection of routes
  302. *
  303. * @return DumperPrefixCollection
  304. */
  305. private function buildPrefixTree(DumperCollection $collection)
  306. {
  307. $tree = new DumperPrefixCollection();
  308. $current = $tree;
  309. foreach ($collection as $route) {
  310. $current = $current->addPrefixRoute($route);
  311. }
  312. $tree->mergeSlashNodes();
  313. return $tree;
  314. }
  315. }