菜谱项目

PhpMatcherDumper.php 14KB

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