Drupal investigation

PhpMatcherDumper.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 = $route->getMethods();
  188. // GET and HEAD are equivalent
  189. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  190. $methods[] = 'HEAD';
  191. }
  192. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
  193. if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
  194. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  195. $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  196. $hasTrailingSlash = true;
  197. } else {
  198. $conditions[] = sprintf('$pathinfo === %s', var_export(str_replace('\\', '', $m['url']), true));
  199. }
  200. } else {
  201. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  202. $conditions[] = sprintf('0 === strpos($pathinfo, %s)', var_export($compiledRoute->getStaticPrefix(), true));
  203. }
  204. $regex = $compiledRoute->getRegex();
  205. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  206. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  207. $hasTrailingSlash = true;
  208. }
  209. $conditions[] = sprintf('preg_match(%s, $pathinfo, $matches)', var_export($regex, true));
  210. $matches = true;
  211. }
  212. if ($compiledRoute->getHostVariables()) {
  213. $hostMatches = true;
  214. }
  215. if ($route->getCondition()) {
  216. $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
  217. }
  218. $conditions = implode(' && ', $conditions);
  219. $code .= <<<EOF
  220. // $name
  221. if ($conditions) {
  222. EOF;
  223. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  224. if ($methods) {
  225. if (1 === count($methods)) {
  226. $code .= <<<EOF
  227. if (\$this->context->getMethod() != '$methods[0]') {
  228. \$allow[] = '$methods[0]';
  229. goto $gotoname;
  230. }
  231. EOF;
  232. } else {
  233. $methods = implode("', '", $methods);
  234. $code .= <<<EOF
  235. if (!in_array(\$this->context->getMethod(), array('$methods'))) {
  236. \$allow = array_merge(\$allow, array('$methods'));
  237. goto $gotoname;
  238. }
  239. EOF;
  240. }
  241. }
  242. if ($hasTrailingSlash) {
  243. $code .= <<<EOF
  244. if (substr(\$pathinfo, -1) !== '/') {
  245. return \$this->redirect(\$pathinfo.'/', '$name');
  246. }
  247. EOF;
  248. }
  249. if ($schemes = $route->getSchemes()) {
  250. if (!$supportsRedirections) {
  251. throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  252. }
  253. $schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
  254. $code .= <<<EOF
  255. \$requiredSchemes = $schemes;
  256. if (!isset(\$requiredSchemes[\$this->context->getScheme()])) {
  257. return \$this->redirect(\$pathinfo, '$name', key(\$requiredSchemes));
  258. }
  259. EOF;
  260. }
  261. // optimize parameters array
  262. if ($matches || $hostMatches) {
  263. $vars = array();
  264. if ($hostMatches) {
  265. $vars[] = '$hostMatches';
  266. }
  267. if ($matches) {
  268. $vars[] = '$matches';
  269. }
  270. $vars[] = "array('_route' => '$name')";
  271. $code .= sprintf(
  272. " return \$this->mergeDefaults(array_replace(%s), %s);\n",
  273. implode(', ', $vars),
  274. str_replace("\n", '', var_export($route->getDefaults(), true))
  275. );
  276. } elseif ($route->getDefaults()) {
  277. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
  278. } else {
  279. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  280. }
  281. $code .= " }\n";
  282. if ($methods) {
  283. $code .= " $gotoname:\n";
  284. }
  285. return $code;
  286. }
  287. /**
  288. * Groups consecutive routes having the same host regex.
  289. *
  290. * The result is a collection of collections of routes having the same host regex.
  291. *
  292. * @param RouteCollection $routes A flat RouteCollection
  293. *
  294. * @return DumperCollection A collection with routes grouped by host regex in sub-collections
  295. */
  296. private function groupRoutesByHostRegex(RouteCollection $routes)
  297. {
  298. $groups = new DumperCollection();
  299. $currentGroup = new DumperCollection();
  300. $currentGroup->setAttribute('host_regex', null);
  301. $groups->add($currentGroup);
  302. foreach ($routes as $name => $route) {
  303. $hostRegex = $route->compile()->getHostRegex();
  304. if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
  305. $currentGroup = new DumperCollection();
  306. $currentGroup->setAttribute('host_regex', $hostRegex);
  307. $groups->add($currentGroup);
  308. }
  309. $currentGroup->add(new DumperRoute($name, $route));
  310. }
  311. return $groups;
  312. }
  313. /**
  314. * Organizes the routes into a prefix tree.
  315. *
  316. * Routes order is preserved such that traversing the tree will traverse the
  317. * routes in the origin order.
  318. *
  319. * @param DumperCollection $collection A collection of routes
  320. *
  321. * @return DumperPrefixCollection
  322. */
  323. private function buildPrefixTree(DumperCollection $collection)
  324. {
  325. $tree = new DumperPrefixCollection();
  326. $current = $tree;
  327. foreach ($collection as $route) {
  328. $current = $current->addPrefixRoute($route);
  329. }
  330. $tree->mergeSlashNodes();
  331. return $tree;
  332. }
  333. private function getExpressionLanguage()
  334. {
  335. if (null === $this->expressionLanguage) {
  336. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  337. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  338. }
  339. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  340. }
  341. return $this->expressionLanguage;
  342. }
  343. }