PageRenderTime 27ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php

https://github.com/Exercise/symfony
PHP | 289 lines | 167 code | 43 blank | 79 comment | 39 complexity | e6bb0c211ebbfc204b5f1525ee46f710 MD5 | raw file
  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. */
  19. class PhpMatcherDumper extends MatcherDumper
  20. {
  21. /**
  22. * Dumps a set of routes to a PHP class.
  23. *
  24. * Available options:
  25. *
  26. * * class: The class name
  27. * * base_class: The base class name
  28. *
  29. * @param array $options An array of options
  30. *
  31. * @return string A PHP class representing the matcher class
  32. */
  33. public function dump(array $options = array())
  34. {
  35. $options = array_merge(array(
  36. 'class' => 'ProjectUrlMatcher',
  37. 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  38. ), $options);
  39. // trailing slash support is only enabled if we know how to redirect the user
  40. $interfaces = class_implements($options['base_class']);
  41. $supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
  42. return <<<EOF
  43. <?php
  44. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  45. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  46. use Symfony\Component\Routing\RequestContext;
  47. /**
  48. * {$options['class']}
  49. *
  50. * This class has been auto-generated
  51. * by the Symfony Routing Component.
  52. */
  53. class {$options['class']} extends {$options['base_class']}
  54. {
  55. /**
  56. * Constructor.
  57. */
  58. public function __construct(RequestContext \$context)
  59. {
  60. \$this->context = \$context;
  61. }
  62. {$this->generateMatchMethod($supportsRedirections)}
  63. }
  64. EOF;
  65. }
  66. /**
  67. * Generates the code for the match method implementing UrlMatcherInterface.
  68. *
  69. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  70. *
  71. * @return string Match method as PHP code
  72. */
  73. private function generateMatchMethod($supportsRedirections)
  74. {
  75. $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
  76. return <<<EOF
  77. public function match(\$pathinfo)
  78. {
  79. \$allow = array();
  80. \$pathinfo = rawurldecode(\$pathinfo);
  81. $code
  82. throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
  83. }
  84. EOF;
  85. }
  86. /**
  87. * Counts the number of routes as direct child of the RouteCollection.
  88. *
  89. * @param RouteCollection $routes A RouteCollection instance
  90. *
  91. * @return integer Number of Routes
  92. */
  93. private function countDirectChildRoutes(RouteCollection $routes)
  94. {
  95. $count = 0;
  96. foreach ($routes as $route) {
  97. if ($route instanceof Route) {
  98. $count++;
  99. }
  100. }
  101. return $count;
  102. }
  103. /**
  104. * Generates PHP code recursively to match a RouteCollection with all child routes and child collections.
  105. *
  106. * @param RouteCollection $routes A RouteCollection instance
  107. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  108. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  109. *
  110. * @return string PHP code
  111. */
  112. private function compileRoutes(RouteCollection $routes, $supportsRedirections, $parentPrefix = null)
  113. {
  114. $code = '';
  115. $prefix = $routes->getPrefix();
  116. $countDirectChildRoutes = $this->countDirectChildRoutes($routes);
  117. $countAllChildRoutes = count($routes->all());
  118. // Can the matching be optimized by wrapping it with the prefix condition
  119. // - no need to optimize if current prefix is the same as the parent prefix
  120. // - if $countDirectChildRoutes === 0, the sub-collections can do their own optimizations (in case there are any)
  121. // - it's not worth wrapping a single child route
  122. // - prefixes with variables cannot be optimized because routes within the collection might have different requirements for the same variable
  123. $optimizable = '' !== $prefix && $prefix !== $parentPrefix && $countDirectChildRoutes > 0 && $countAllChildRoutes > 1 && false === strpos($prefix, '{');
  124. if ($optimizable) {
  125. $code .= sprintf(" if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));
  126. }
  127. foreach ($routes as $name => $route) {
  128. if ($route instanceof Route) {
  129. // a single route in a sub-collection is not wrapped so it should do its own optimization in ->compileRoute with $parentPrefix = null
  130. $code .= $this->compileRoute($route, $name, $supportsRedirections, 1 === $countAllChildRoutes ? null : $prefix)."\n";
  131. } elseif ($countAllChildRoutes - $countDirectChildRoutes > 0) { // we can stop iterating recursively if we already know there are no more routes
  132. $code .= $this->compileRoutes($route, $supportsRedirections, $prefix);
  133. }
  134. }
  135. if ($optimizable) {
  136. $code .= " }\n\n";
  137. // apply extra indention at each line (except empty ones)
  138. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  139. }
  140. return $code;
  141. }
  142. /**
  143. * Compiles a single Route to PHP code used to match it against the path info.
  144. *
  145. * @param Route $routes A Route instance
  146. * @param string $name The name of the Route
  147. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  148. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  149. *
  150. * @return string PHP code
  151. */
  152. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  153. {
  154. $code = '';
  155. $compiledRoute = $route->compile();
  156. $conditions = array();
  157. $hasTrailingSlash = false;
  158. $matches = false;
  159. $methods = array();
  160. if ($req = $route->getRequirement('_method')) {
  161. $methods = explode('|', strtoupper($req));
  162. // GET and HEAD are equivalent
  163. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  164. $methods[] = 'HEAD';
  165. }
  166. }
  167. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
  168. if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
  169. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  170. $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  171. $hasTrailingSlash = true;
  172. } else {
  173. $conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
  174. }
  175. } else {
  176. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  177. $conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
  178. }
  179. $regex = $compiledRoute->getRegex();
  180. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  181. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  182. $hasTrailingSlash = true;
  183. }
  184. $conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));
  185. $matches = true;
  186. }
  187. $conditions = implode(' && ', $conditions);
  188. $code .= <<<EOF
  189. // $name
  190. if ($conditions) {
  191. EOF;
  192. if ($methods) {
  193. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  194. if (1 === count($methods)) {
  195. $code .= <<<EOF
  196. if (\$this->context->getMethod() != '$methods[0]') {
  197. \$allow[] = '$methods[0]';
  198. goto $gotoname;
  199. }
  200. EOF;
  201. } else {
  202. $methods = implode("', '", $methods);
  203. $code .= <<<EOF
  204. if (!in_array(\$this->context->getMethod(), array('$methods'))) {
  205. \$allow = array_merge(\$allow, array('$methods'));
  206. goto $gotoname;
  207. }
  208. EOF;
  209. }
  210. }
  211. if ($hasTrailingSlash) {
  212. $code .= <<<EOF
  213. if (substr(\$pathinfo, -1) !== '/') {
  214. return \$this->redirect(\$pathinfo.'/', '$name');
  215. }
  216. EOF;
  217. }
  218. if ($scheme = $route->getRequirement('_scheme')) {
  219. if (!$supportsRedirections) {
  220. throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  221. }
  222. $code .= <<<EOF
  223. if (\$this->context->getScheme() !== '$scheme') {
  224. return \$this->redirect(\$pathinfo, '$name', '$scheme');
  225. }
  226. EOF;
  227. }
  228. // optimize parameters array
  229. if (true === $matches && $compiledRoute->getDefaults()) {
  230. $code .= sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));\n"
  231. , str_replace("\n", '', var_export($compiledRoute->getDefaults(), true)), $name);
  232. } elseif (true === $matches) {
  233. $code .= sprintf(" \$matches['_route'] = '%s';\n", $name);
  234. $code .= " return \$matches;\n";
  235. } elseif ($compiledRoute->getDefaults()) {
  236. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_merge($compiledRoute->getDefaults(), array('_route' => $name)), true)));
  237. } else {
  238. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  239. }
  240. $code .= " }\n";
  241. if ($methods) {
  242. $code .= " $gotoname:\n";
  243. }
  244. return $code;
  245. }
  246. }