No Description

PhpMatcherDumper.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  14. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  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 = array();
  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 = array())
  42. {
  43. $options = array_replace(array(
  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. * {$options['class']}
  57. *
  58. * This class has been auto-generated
  59. * by the Symfony Routing Component.
  60. */
  61. class {$options['class']} extends {$options['base_class']}
  62. {
  63. /**
  64. * Constructor.
  65. */
  66. public function __construct(RequestContext \$context)
  67. {
  68. \$this->context = \$context;
  69. }
  70. {$this->generateMatchMethod($supportsRedirections)}
  71. }
  72. EOF;
  73. }
  74. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  75. {
  76. $this->expressionLanguageProviders[] = $provider;
  77. }
  78. /**
  79. * Generates the code for the match method implementing UrlMatcherInterface.
  80. *
  81. * @param bool $supportsRedirections Whether redirections are supported by the base class
  82. *
  83. * @return string Match method as PHP code
  84. */
  85. private function generateMatchMethod($supportsRedirections)
  86. {
  87. $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
  88. return <<<EOF
  89. public function match(\$pathinfo)
  90. {
  91. \$allow = array();
  92. \$pathinfo = rawurldecode(\$pathinfo);
  93. \$context = \$this->context;
  94. \$request = \$this->request;
  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 = \$this->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->buildPrefixTree($collection);
  122. $groupCode = $this->compilePrefixRoutes($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. return $code;
  133. }
  134. /**
  135. * Generates PHP code recursively to match a tree of routes.
  136. *
  137. * @param DumperPrefixCollection $collection A DumperPrefixCollection instance
  138. * @param bool $supportsRedirections Whether redirections are supported by the base class
  139. * @param string $parentPrefix Prefix of the parent collection
  140. *
  141. * @return string PHP code
  142. */
  143. private function compilePrefixRoutes(DumperPrefixCollection $collection, $supportsRedirections, $parentPrefix = '')
  144. {
  145. $code = '';
  146. $prefix = $collection->getPrefix();
  147. $optimizable = 1 < strlen($prefix) && 1 < count($collection->all());
  148. $optimizedPrefix = $parentPrefix;
  149. if ($optimizable) {
  150. $optimizedPrefix = $prefix;
  151. $code .= sprintf(" if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));
  152. }
  153. foreach ($collection as $route) {
  154. if ($route instanceof DumperCollection) {
  155. $code .= $this->compilePrefixRoutes($route, $supportsRedirections, $optimizedPrefix);
  156. } else {
  157. $code .= $this->compileRoute($route->getRoute(), $route->getName(), $supportsRedirections, $optimizedPrefix)."\n";
  158. }
  159. }
  160. if ($optimizable) {
  161. $code .= " }\n\n";
  162. // apply extra indention at each line (except empty ones)
  163. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  164. }
  165. return $code;
  166. }
  167. /**
  168. * Compiles a single Route to PHP code used to match it against the path info.
  169. *
  170. * @param Route $route A Route instance
  171. * @param string $name The name of the Route
  172. * @param bool $supportsRedirections Whether redirections are supported by the base class
  173. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  174. *
  175. * @return string PHP code
  176. *
  177. * @throws \LogicException
  178. */
  179. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  180. {
  181. $code = '';
  182. $compiledRoute = $route->compile();
  183. $conditions = array();
  184. $hasTrailingSlash = false;
  185. $matches = false;
  186. $hostMatches = false;
  187. $methods = array();
  188. if ($req = $route->getRequirement('_method')) {
  189. $methods = explode('|', strtoupper($req));
  190. // GET and HEAD are equivalent
  191. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  192. $methods[] = 'HEAD';
  193. }
  194. }
  195. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
  196. if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
  197. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  198. $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  199. $hasTrailingSlash = true;
  200. } else {
  201. $conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
  202. }
  203. } else {
  204. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  205. $conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
  206. }
  207. $regex = $compiledRoute->getRegex();
  208. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  209. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  210. $hasTrailingSlash = true;
  211. }
  212. $conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));
  213. $matches = true;
  214. }
  215. if ($compiledRoute->getHostVariables()) {
  216. $hostMatches = true;
  217. }
  218. if ($route->getCondition()) {
  219. $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
  220. }
  221. $conditions = implode(' && ', $conditions);
  222. $code .= <<<EOF
  223. // $name
  224. if ($conditions) {
  225. EOF;
  226. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  227. if ($methods) {
  228. if (1 === count($methods)) {
  229. $code .= <<<EOF
  230. if (\$this->context->getMethod() != '$methods[0]') {
  231. \$allow[] = '$methods[0]';
  232. goto $gotoname;
  233. }
  234. EOF;
  235. } else {
  236. $methods = implode("', '", $methods);
  237. $code .= <<<EOF
  238. if (!in_array(\$this->context->getMethod(), array('$methods'))) {
  239. \$allow = array_merge(\$allow, array('$methods'));
  240. goto $gotoname;
  241. }
  242. EOF;
  243. }
  244. }
  245. if ($hasTrailingSlash) {
  246. $code .= <<<EOF
  247. if (substr(\$pathinfo, -1) !== '/') {
  248. return \$this->redirect(\$pathinfo.'/', '$name');
  249. }
  250. EOF;
  251. }
  252. if ($schemes = $route->getSchemes()) {
  253. if (!$supportsRedirections) {
  254. throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  255. }
  256. $schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
  257. $code .= <<<EOF
  258. \$requiredSchemes = $schemes;
  259. if (!isset(\$requiredSchemes[\$this->context->getScheme()])) {
  260. return \$this->redirect(\$pathinfo, '$name', key(\$requiredSchemes));
  261. }
  262. EOF;
  263. }
  264. // optimize parameters array
  265. if ($matches || $hostMatches) {
  266. $vars = array();
  267. if ($hostMatches) {
  268. $vars[] = '$hostMatches';
  269. }
  270. if ($matches) {
  271. $vars[] = '$matches';
  272. }
  273. $vars[] = "array('_route' => '$name')";
  274. $code .= sprintf(
  275. " return \$this->mergeDefaults(array_replace(%s), %s);\n",
  276. implode(', ', $vars),
  277. str_replace("\n", '', var_export($route->getDefaults(), true))
  278. );
  279. } elseif ($route->getDefaults()) {
  280. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
  281. } else {
  282. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  283. }
  284. $code .= " }\n";
  285. if ($methods) {
  286. $code .= " $gotoname:\n";
  287. }
  288. return $code;
  289. }
  290. /**
  291. * Groups consecutive routes having the same host regex.
  292. *
  293. * The result is a collection of collections of routes having the same host regex.
  294. *
  295. * @param RouteCollection $routes A flat RouteCollection
  296. *
  297. * @return DumperCollection A collection with routes grouped by host regex in sub-collections
  298. */
  299. private function groupRoutesByHostRegex(RouteCollection $routes)
  300. {
  301. $groups = new DumperCollection();
  302. $currentGroup = new DumperCollection();
  303. $currentGroup->setAttribute('host_regex', null);
  304. $groups->add($currentGroup);
  305. foreach ($routes as $name => $route) {
  306. $hostRegex = $route->compile()->getHostRegex();
  307. if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
  308. $currentGroup = new DumperCollection();
  309. $currentGroup->setAttribute('host_regex', $hostRegex);
  310. $groups->add($currentGroup);
  311. }
  312. $currentGroup->add(new DumperRoute($name, $route));
  313. }
  314. return $groups;
  315. }
  316. /**
  317. * Organizes the routes into a prefix tree.
  318. *
  319. * Routes order is preserved such that traversing the tree will traverse the
  320. * routes in the origin order.
  321. *
  322. * @param DumperCollection $collection A collection of routes
  323. *
  324. * @return DumperPrefixCollection
  325. */
  326. private function buildPrefixTree(DumperCollection $collection)
  327. {
  328. $tree = new DumperPrefixCollection();
  329. $current = $tree;
  330. foreach ($collection as $route) {
  331. $current = $current->addPrefixRoute($route);
  332. }
  333. $tree->mergeSlashNodes();
  334. return $tree;
  335. }
  336. private function getExpressionLanguage()
  337. {
  338. if (null === $this->expressionLanguage) {
  339. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  340. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  341. }
  342. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  343. }
  344. return $this->expressionLanguage;
  345. }
  346. }