PhpMatcherDumper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. \$trimmedPathinfo = rtrim(\$pathinfo, '/');
  94. \$context = \$this->context;
  95. \$request = \$this->request;
  96. \$requestMethod = \$canonicalMethod = \$context->getMethod();
  97. \$scheme = \$context->getScheme();
  98. if ('HEAD' === \$requestMethod) {
  99. \$canonicalMethod = 'GET';
  100. }
  101. $code
  102. throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
  103. }
  104. EOF;
  105. }
  106. /**
  107. * Generates PHP code to match a RouteCollection with all its routes.
  108. *
  109. * @param RouteCollection $routes A RouteCollection instance
  110. * @param bool $supportsRedirections Whether redirections are supported by the base class
  111. *
  112. * @return string PHP code
  113. */
  114. private function compileRoutes(RouteCollection $routes, $supportsRedirections)
  115. {
  116. $fetchedHost = false;
  117. $groups = $this->groupRoutesByHostRegex($routes);
  118. $code = '';
  119. foreach ($groups as $collection) {
  120. if (null !== $regex = $collection->getAttribute('host_regex')) {
  121. if (!$fetchedHost) {
  122. $code .= " \$host = \$context->getHost();\n\n";
  123. $fetchedHost = true;
  124. }
  125. $code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
  126. }
  127. $tree = $this->buildStaticPrefixCollection($collection);
  128. $groupCode = $this->compileStaticPrefixRoutes($tree, $supportsRedirections);
  129. if (null !== $regex) {
  130. // apply extra indention at each line (except empty ones)
  131. $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
  132. $code .= $groupCode;
  133. $code .= " }\n\n";
  134. } else {
  135. $code .= $groupCode;
  136. }
  137. }
  138. return $code;
  139. }
  140. private function buildStaticPrefixCollection(DumperCollection $collection)
  141. {
  142. $prefixCollection = new StaticPrefixCollection();
  143. foreach ($collection as $dumperRoute) {
  144. $prefix = $dumperRoute->getRoute()->compile()->getStaticPrefix();
  145. $prefixCollection->addRoute($prefix, $dumperRoute);
  146. }
  147. $prefixCollection->optimizeGroups();
  148. return $prefixCollection;
  149. }
  150. /**
  151. * Generates PHP code to match a tree of routes.
  152. *
  153. * @param StaticPrefixCollection $collection A StaticPrefixCollection instance
  154. * @param bool $supportsRedirections Whether redirections are supported by the base class
  155. * @param string $ifOrElseIf Either "if" or "elseif" to influence chaining.
  156. *
  157. * @return string PHP code
  158. */
  159. private function compileStaticPrefixRoutes(StaticPrefixCollection $collection, $supportsRedirections, $ifOrElseIf = 'if')
  160. {
  161. $code = '';
  162. $prefix = $collection->getPrefix();
  163. if (!empty($prefix) && '/' !== $prefix) {
  164. $code .= sprintf(" %s (0 === strpos(\$pathinfo, %s)) {\n", $ifOrElseIf, var_export($prefix, true));
  165. }
  166. $ifOrElseIf = 'if';
  167. foreach ($collection->getItems() as $route) {
  168. if ($route instanceof StaticPrefixCollection) {
  169. $code .= $this->compileStaticPrefixRoutes($route, $supportsRedirections, $ifOrElseIf);
  170. $ifOrElseIf = 'elseif';
  171. } else {
  172. $code .= $this->compileRoute($route[1]->getRoute(), $route[1]->getName(), $supportsRedirections, $prefix)."\n";
  173. $ifOrElseIf = 'if';
  174. }
  175. }
  176. if (!empty($prefix) && '/' !== $prefix) {
  177. $code .= " }\n\n";
  178. // apply extra indention at each line (except empty ones)
  179. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  180. }
  181. return $code;
  182. }
  183. /**
  184. * Compiles a single Route to PHP code used to match it against the path info.
  185. *
  186. * @param Route $route A Route instance
  187. * @param string $name The name of the Route
  188. * @param bool $supportsRedirections Whether redirections are supported by the base class
  189. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  190. *
  191. * @return string PHP code
  192. *
  193. * @throws \LogicException
  194. */
  195. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  196. {
  197. $code = '';
  198. $compiledRoute = $route->compile();
  199. $conditions = array();
  200. $hasTrailingSlash = false;
  201. $matches = false;
  202. $hostMatches = false;
  203. $methods = $route->getMethods();
  204. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods) || in_array('GET', $methods));
  205. $regex = $compiledRoute->getRegex();
  206. if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#'.(substr($regex, -1) === 'u' ? 'u' : ''), $regex, $m)) {
  207. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  208. $conditions[] = sprintf('%s === $trimmedPathinfo', var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  209. $hasTrailingSlash = true;
  210. } else {
  211. $conditions[] = sprintf('%s === $pathinfo', var_export(str_replace('\\', '', $m['url']), true));
  212. }
  213. } else {
  214. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  215. $conditions[] = sprintf('0 === strpos($pathinfo, %s)', var_export($compiledRoute->getStaticPrefix(), true));
  216. }
  217. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  218. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  219. $hasTrailingSlash = true;
  220. }
  221. $conditions[] = sprintf('preg_match(%s, $pathinfo, $matches)', var_export($regex, true));
  222. $matches = true;
  223. }
  224. if ($compiledRoute->getHostVariables()) {
  225. $hostMatches = true;
  226. }
  227. if ($route->getCondition()) {
  228. $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
  229. }
  230. $conditions = implode(' && ', $conditions);
  231. $code .= <<<EOF
  232. // $name
  233. if ($conditions) {
  234. EOF;
  235. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  236. if ($methods) {
  237. if (1 === count($methods)) {
  238. if ($methods[0] === 'HEAD') {
  239. $code .= <<<EOF
  240. if ('HEAD' !== \$requestMethod) {
  241. \$allow[] = 'HEAD';
  242. goto $gotoname;
  243. }
  244. EOF;
  245. } else {
  246. $code .= <<<EOF
  247. if ('$methods[0]' !== \$canonicalMethod) {
  248. \$allow[] = '$methods[0]';
  249. goto $gotoname;
  250. }
  251. EOF;
  252. }
  253. } else {
  254. $methodVariable = 'requestMethod';
  255. if (in_array('GET', $methods)) {
  256. // Since we treat HEAD requests like GET requests we don't need to match it.
  257. $methodVariable = 'canonicalMethod';
  258. $methods = array_filter($methods, function ($method) { return 'HEAD' !== $method; });
  259. }
  260. if (1 === count($methods)) {
  261. $code .= <<<EOF
  262. if ('$methods[0]' !== \$$methodVariable) {
  263. \$allow[] = '$methods[0]';
  264. goto $gotoname;
  265. }
  266. EOF;
  267. } else {
  268. $methods = implode("', '", $methods);
  269. $code .= <<<EOF
  270. if (!in_array(\$$methodVariable, array('$methods'))) {
  271. \$allow = array_merge(\$allow, array('$methods'));
  272. goto $gotoname;
  273. }
  274. EOF;
  275. }
  276. }
  277. }
  278. if ($hasTrailingSlash) {
  279. $code .= <<<EOF
  280. if (substr(\$pathinfo, -1) !== '/') {
  281. return \$this->redirect(\$pathinfo.'/', '$name');
  282. }
  283. EOF;
  284. }
  285. if ($schemes = $route->getSchemes()) {
  286. if (!$supportsRedirections) {
  287. throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  288. }
  289. $schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
  290. $code .= <<<EOF
  291. \$requiredSchemes = $schemes;
  292. if (!isset(\$requiredSchemes[\$scheme])) {
  293. return \$this->redirect(\$pathinfo, '$name', key(\$requiredSchemes));
  294. }
  295. EOF;
  296. }
  297. // optimize parameters array
  298. if ($matches || $hostMatches) {
  299. $vars = array();
  300. if ($hostMatches) {
  301. $vars[] = '$hostMatches';
  302. }
  303. if ($matches) {
  304. $vars[] = '$matches';
  305. }
  306. $vars[] = "array('_route' => '$name')";
  307. $code .= sprintf(
  308. " return \$this->mergeDefaults(array_replace(%s), %s);\n",
  309. implode(', ', $vars),
  310. str_replace("\n", '', var_export($route->getDefaults(), true))
  311. );
  312. } elseif ($route->getDefaults()) {
  313. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
  314. } else {
  315. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  316. }
  317. $code .= " }\n";
  318. if ($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. }