PageRenderTime 26ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/routing/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php

https://gitlab.com/daniruizcamacho/pfcascensores
PHP | 398 lines | 235 code | 66 blank | 97 comment | 48 complexity | 9daade9ffbdeff369f03818ef2f73ce2 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. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  14. /**
  15. * PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. * @author Tobias Schultze <http://tobion.de>
  19. * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
  20. */
  21. class PhpMatcherDumper extends MatcherDumper
  22. {
  23. private $expressionLanguage;
  24. /**
  25. * Dumps a set of routes to a PHP class.
  26. *
  27. * Available options:
  28. *
  29. * * class: The class name
  30. * * base_class: The base class name
  31. *
  32. * @param array $options An array of options
  33. *
  34. * @return string A PHP class representing the matcher class
  35. */
  36. public function dump(array $options = array())
  37. {
  38. $options = array_replace(array(
  39. 'class' => 'ProjectUrlMatcher',
  40. 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  41. ), $options);
  42. // trailing slash support is only enabled if we know how to redirect the user
  43. $interfaces = class_implements($options['base_class']);
  44. $supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
  45. return <<<EOF
  46. <?php
  47. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  48. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  49. use Symfony\Component\Routing\RequestContext;
  50. /**
  51. * {$options['class']}
  52. *
  53. * This class has been auto-generated
  54. * by the Symfony Routing Component.
  55. */
  56. class {$options['class']} extends {$options['base_class']}
  57. {
  58. /**
  59. * Constructor.
  60. */
  61. public function __construct(RequestContext \$context)
  62. {
  63. \$this->context = \$context;
  64. }
  65. {$this->generateMatchMethod($supportsRedirections)}
  66. }
  67. EOF;
  68. }
  69. /**
  70. * Generates the code for the match method implementing UrlMatcherInterface.
  71. *
  72. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  73. *
  74. * @return string Match method as PHP code
  75. */
  76. private function generateMatchMethod($supportsRedirections)
  77. {
  78. $code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
  79. return <<<EOF
  80. public function match(\$pathinfo)
  81. {
  82. \$allow = array();
  83. \$pathinfo = rawurldecode(\$pathinfo);
  84. \$context = \$this->context;
  85. \$request = \$this->request;
  86. $code
  87. throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
  88. }
  89. EOF;
  90. }
  91. /**
  92. * Generates PHP code to match a RouteCollection with all its routes.
  93. *
  94. * @param RouteCollection $routes A RouteCollection instance
  95. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  96. *
  97. * @return string PHP code
  98. */
  99. private function compileRoutes(RouteCollection $routes, $supportsRedirections)
  100. {
  101. $fetchedHost = false;
  102. $groups = $this->groupRoutesByHostRegex($routes);
  103. $code = '';
  104. foreach ($groups as $collection) {
  105. if (null !== $regex = $collection->getAttribute('host_regex')) {
  106. if (!$fetchedHost) {
  107. $code .= " \$host = \$this->context->getHost();\n\n";
  108. $fetchedHost = true;
  109. }
  110. $code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
  111. }
  112. $tree = $this->buildPrefixTree($collection);
  113. $groupCode = $this->compilePrefixRoutes($tree, $supportsRedirections);
  114. if (null !== $regex) {
  115. // apply extra indention at each line (except empty ones)
  116. $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
  117. $code .= $groupCode;
  118. $code .= " }\n\n";
  119. } else {
  120. $code .= $groupCode;
  121. }
  122. }
  123. return $code;
  124. }
  125. /**
  126. * Generates PHP code recursively to match a tree of routes
  127. *
  128. * @param DumperPrefixCollection $collection A DumperPrefixCollection instance
  129. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  130. * @param string $parentPrefix Prefix of the parent collection
  131. *
  132. * @return string PHP code
  133. */
  134. private function compilePrefixRoutes(DumperPrefixCollection $collection, $supportsRedirections, $parentPrefix = '')
  135. {
  136. $code = '';
  137. $prefix = $collection->getPrefix();
  138. $optimizable = 1 < strlen($prefix) && 1 < count($collection->all());
  139. $optimizedPrefix = $parentPrefix;
  140. if ($optimizable) {
  141. $optimizedPrefix = $prefix;
  142. $code .= sprintf(" if (0 === strpos(\$pathinfo, %s)) {\n", var_export($prefix, true));
  143. }
  144. foreach ($collection as $route) {
  145. if ($route instanceof DumperCollection) {
  146. $code .= $this->compilePrefixRoutes($route, $supportsRedirections, $optimizedPrefix);
  147. } else {
  148. $code .= $this->compileRoute($route->getRoute(), $route->getName(), $supportsRedirections, $optimizedPrefix)."\n";
  149. }
  150. }
  151. if ($optimizable) {
  152. $code .= " }\n\n";
  153. // apply extra indention at each line (except empty ones)
  154. $code = preg_replace('/^.{2,}$/m', ' $0', $code);
  155. }
  156. return $code;
  157. }
  158. /**
  159. * Compiles a single Route to PHP code used to match it against the path info.
  160. *
  161. * @param Route $route A Route instance
  162. * @param string $name The name of the Route
  163. * @param Boolean $supportsRedirections Whether redirections are supported by the base class
  164. * @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
  165. *
  166. * @return string PHP code
  167. *
  168. * @throws \LogicException
  169. */
  170. private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
  171. {
  172. $code = '';
  173. $compiledRoute = $route->compile();
  174. $conditions = array();
  175. $hasTrailingSlash = false;
  176. $matches = false;
  177. $hostMatches = false;
  178. $methods = array();
  179. if ($req = $route->getRequirement('_method')) {
  180. $methods = explode('|', strtoupper($req));
  181. // GET and HEAD are equivalent
  182. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  183. $methods[] = 'HEAD';
  184. }
  185. }
  186. $supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
  187. if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
  188. if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
  189. $conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
  190. $hasTrailingSlash = true;
  191. } else {
  192. $conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
  193. }
  194. } else {
  195. if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
  196. $conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
  197. }
  198. $regex = $compiledRoute->getRegex();
  199. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  200. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  201. $hasTrailingSlash = true;
  202. }
  203. $conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));
  204. $matches = true;
  205. }
  206. if ($compiledRoute->getHostVariables()) {
  207. $hostMatches = true;
  208. }
  209. if ($route->getCondition()) {
  210. $conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
  211. }
  212. $conditions = implode(' && ', $conditions);
  213. $code .= <<<EOF
  214. // $name
  215. if ($conditions) {
  216. EOF;
  217. $gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
  218. if ($methods) {
  219. if (1 === count($methods)) {
  220. $code .= <<<EOF
  221. if (\$this->context->getMethod() != '$methods[0]') {
  222. \$allow[] = '$methods[0]';
  223. goto $gotoname;
  224. }
  225. EOF;
  226. } else {
  227. $methods = implode("', '", $methods);
  228. $code .= <<<EOF
  229. if (!in_array(\$this->context->getMethod(), array('$methods'))) {
  230. \$allow = array_merge(\$allow, array('$methods'));
  231. goto $gotoname;
  232. }
  233. EOF;
  234. }
  235. }
  236. if ($hasTrailingSlash) {
  237. $code .= <<<EOF
  238. if (substr(\$pathinfo, -1) !== '/') {
  239. return \$this->redirect(\$pathinfo.'/', '$name');
  240. }
  241. EOF;
  242. }
  243. if ($scheme = $route->getRequirement('_scheme')) {
  244. if (!$supportsRedirections) {
  245. throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
  246. }
  247. $code .= <<<EOF
  248. if (\$this->context->getScheme() !== '$scheme') {
  249. return \$this->redirect(\$pathinfo, '$name', '$scheme');
  250. }
  251. EOF;
  252. }
  253. // optimize parameters array
  254. if ($matches || $hostMatches) {
  255. $vars = array();
  256. if ($hostMatches) {
  257. $vars[] = '$hostMatches';
  258. }
  259. if ($matches) {
  260. $vars[] = '$matches';
  261. }
  262. $vars[] = "array('_route' => '$name')";
  263. $code .= sprintf(" return \$this->mergeDefaults(array_replace(%s), %s);\n"
  264. , implode(', ', $vars), str_replace("\n", '', var_export($route->getDefaults(), true)));
  265. } elseif ($route->getDefaults()) {
  266. $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
  267. } else {
  268. $code .= sprintf(" return array('_route' => '%s');\n", $name);
  269. }
  270. $code .= " }\n";
  271. if ($methods) {
  272. $code .= " $gotoname:\n";
  273. }
  274. return $code;
  275. }
  276. /**
  277. * Groups consecutive routes having the same host regex.
  278. *
  279. * The result is a collection of collections of routes having the same host regex.
  280. *
  281. * @param RouteCollection $routes A flat RouteCollection
  282. *
  283. * @return DumperCollection A collection with routes grouped by host regex in sub-collections
  284. */
  285. private function groupRoutesByHostRegex(RouteCollection $routes)
  286. {
  287. $groups = new DumperCollection();
  288. $currentGroup = new DumperCollection();
  289. $currentGroup->setAttribute('host_regex', null);
  290. $groups->add($currentGroup);
  291. foreach ($routes as $name => $route) {
  292. $hostRegex = $route->compile()->getHostRegex();
  293. if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
  294. $currentGroup = new DumperCollection();
  295. $currentGroup->setAttribute('host_regex', $hostRegex);
  296. $groups->add($currentGroup);
  297. }
  298. $currentGroup->add(new DumperRoute($name, $route));
  299. }
  300. return $groups;
  301. }
  302. /**
  303. * Organizes the routes into a prefix tree.
  304. *
  305. * Routes order is preserved such that traversing the tree will traverse the
  306. * routes in the origin order.
  307. *
  308. * @param DumperCollection $collection A collection of routes
  309. *
  310. * @return DumperPrefixCollection
  311. */
  312. private function buildPrefixTree(DumperCollection $collection)
  313. {
  314. $tree = new DumperPrefixCollection();
  315. $current = $tree;
  316. foreach ($collection as $route) {
  317. $current = $current->addPrefixRoute($route);
  318. }
  319. $tree->mergeSlashNodes();
  320. return $tree;
  321. }
  322. private function getExpressionLanguage()
  323. {
  324. if (null === $this->expressionLanguage) {
  325. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  326. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  327. }
  328. $this->expressionLanguage = new ExpressionLanguage();
  329. }
  330. return $this->expressionLanguage;
  331. }
  332. }