ApacheMatcherDumper.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. @trigger_error('The '.__NAMESPACE__.'\ApacheMatcherDumper class is deprecated since Symfony 2.5 and will be removed in 3.0. It\'s hard to replicate the behaviour of the PHP implementation and the performance gains are minimal.', E_USER_DEPRECATED);
  12. use Symfony\Component\Routing\Route;
  13. /**
  14. * Dumps a set of Apache mod_rewrite rules.
  15. *
  16. * @deprecated since version 2.5, to be removed in 3.0.
  17. * The performance gains are minimal and it's very hard to replicate
  18. * the behavior of PHP implementation.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. * @author Kris Wallsmith <kris@symfony.com>
  22. */
  23. class ApacheMatcherDumper extends MatcherDumper
  24. {
  25. /**
  26. * Dumps a set of Apache mod_rewrite rules.
  27. *
  28. * Available options:
  29. *
  30. * * script_name: The script name (app.php by default)
  31. * * base_uri: The base URI ("" by default)
  32. *
  33. * @return string A string to be used as Apache rewrite rules
  34. *
  35. * @throws \LogicException When the route regex is invalid
  36. */
  37. public function dump(array $options = array())
  38. {
  39. $options = array_merge(array(
  40. 'script_name' => 'app.php',
  41. 'base_uri' => '',
  42. ), $options);
  43. $options['script_name'] = self::escape($options['script_name'], ' ', '\\');
  44. $rules = array("# skip \"real\" requests\nRewriteCond %{REQUEST_FILENAME} -f\nRewriteRule .* - [QSA,L]");
  45. $methodVars = array();
  46. $hostRegexUnique = 0;
  47. $prevHostRegex = '';
  48. foreach ($this->getRoutes()->all() as $name => $route) {
  49. if ($route->getCondition()) {
  50. throw new \LogicException(sprintf('Unable to dump the routes for Apache as route "%s" has a condition.', $name));
  51. }
  52. $compiledRoute = $route->compile();
  53. $hostRegex = $compiledRoute->getHostRegex();
  54. if (null !== $hostRegex && $prevHostRegex !== $hostRegex) {
  55. $prevHostRegex = $hostRegex;
  56. ++$hostRegexUnique;
  57. $rule = array();
  58. $regex = $this->regexToApacheRegex($hostRegex);
  59. $regex = self::escape($regex, ' ', '\\');
  60. $rule[] = sprintf('RewriteCond %%{HTTP:Host} %s', $regex);
  61. $variables = array();
  62. $variables[] = sprintf('E=__ROUTING_host_%s:1', $hostRegexUnique);
  63. foreach ($compiledRoute->getHostVariables() as $i => $variable) {
  64. $variables[] = sprintf('E=__ROUTING_host_%s_%s:%%%d', $hostRegexUnique, $variable, $i + 1);
  65. }
  66. $variables = implode(',', $variables);
  67. $rule[] = sprintf('RewriteRule .? - [%s]', $variables);
  68. $rules[] = implode("\n", $rule);
  69. }
  70. $rules[] = $this->dumpRoute($name, $route, $options, $hostRegexUnique);
  71. $methodVars = array_merge($methodVars, $route->getMethods());
  72. }
  73. if (0 < \count($methodVars)) {
  74. $rule = array('# 405 Method Not Allowed');
  75. $methodVars = array_values(array_unique($methodVars));
  76. if (\in_array('GET', $methodVars) && !\in_array('HEAD', $methodVars)) {
  77. $methodVars[] = 'HEAD';
  78. }
  79. foreach ($methodVars as $i => $methodVar) {
  80. $rule[] = sprintf('RewriteCond %%{ENV:_ROUTING__allow_%s} =1%s', $methodVar, isset($methodVars[$i + 1]) ? ' [OR]' : '');
  81. }
  82. $rule[] = sprintf('RewriteRule .* %s [QSA,L]', $options['script_name']);
  83. $rules[] = implode("\n", $rule);
  84. }
  85. return implode("\n\n", $rules)."\n";
  86. }
  87. /**
  88. * Dumps a single route.
  89. *
  90. * @param string $name Route name
  91. * @param Route $route The route
  92. * @param array $options Options
  93. * @param bool $hostRegexUnique Unique identifier for the host regex
  94. *
  95. * @return string The compiled route
  96. */
  97. private function dumpRoute($name, $route, array $options, $hostRegexUnique)
  98. {
  99. $compiledRoute = $route->compile();
  100. // prepare the apache regex
  101. $regex = $this->regexToApacheRegex($compiledRoute->getRegex());
  102. $regex = '^'.self::escape(preg_quote($options['base_uri']).substr($regex, 1), ' ', '\\');
  103. $methods = $this->getRouteMethods($route);
  104. $hasTrailingSlash = (!$methods || \in_array('HEAD', $methods)) && '/$' === substr($regex, -2) && '^/$' !== $regex;
  105. $variables = array('E=_ROUTING_route:'.$name);
  106. foreach ($compiledRoute->getHostVariables() as $variable) {
  107. $variables[] = sprintf('E=_ROUTING_param_%s:%%{ENV:__ROUTING_host_%s_%s}', $variable, $hostRegexUnique, $variable);
  108. }
  109. foreach ($compiledRoute->getPathVariables() as $i => $variable) {
  110. $variables[] = 'E=_ROUTING_param_'.$variable.':%'.($i + 1);
  111. }
  112. foreach ($this->normalizeValues($route->getDefaults()) as $key => $value) {
  113. $variables[] = 'E=_ROUTING_default_'.$key.':'.strtr($value, array(
  114. ':' => '\\:',
  115. '=' => '\\=',
  116. '\\' => '\\\\',
  117. ' ' => '\\ ',
  118. ));
  119. }
  120. $variables = implode(',', $variables);
  121. $rule = array("# $name");
  122. // method mismatch
  123. if (0 < \count($methods)) {
  124. $allow = array();
  125. foreach ($methods as $method) {
  126. $allow[] = 'E=_ROUTING_allow_'.$method.':1';
  127. }
  128. if ($compiledRoute->getHostRegex()) {
  129. $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
  130. }
  131. $rule[] = "RewriteCond %{REQUEST_URI} $regex";
  132. $rule[] = sprintf('RewriteCond %%{REQUEST_METHOD} !^(%s)$ [NC]', implode('|', $methods));
  133. $rule[] = sprintf('RewriteRule .* - [S=%d,%s]', $hasTrailingSlash ? 2 : 1, implode(',', $allow));
  134. }
  135. // redirect with trailing slash appended
  136. if ($hasTrailingSlash) {
  137. if ($compiledRoute->getHostRegex()) {
  138. $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
  139. }
  140. $rule[] = 'RewriteCond %{REQUEST_URI} '.substr($regex, 0, -2).'$';
  141. $rule[] = 'RewriteRule .* $0/ [QSA,L,R=301]';
  142. }
  143. // the main rule
  144. if ($compiledRoute->getHostRegex()) {
  145. $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
  146. }
  147. $rule[] = "RewriteCond %{REQUEST_URI} $regex";
  148. $rule[] = "RewriteRule .* {$options['script_name']} [QSA,L,$variables]";
  149. return implode("\n", $rule);
  150. }
  151. /**
  152. * Returns methods allowed for a route.
  153. *
  154. * @return array The methods
  155. */
  156. private function getRouteMethods(Route $route)
  157. {
  158. $methods = $route->getMethods();
  159. // GET and HEAD are equivalent
  160. if (\in_array('GET', $methods) && !\in_array('HEAD', $methods)) {
  161. $methods[] = 'HEAD';
  162. }
  163. return $methods;
  164. }
  165. /**
  166. * Converts a regex to make it suitable for mod_rewrite.
  167. *
  168. * @param string $regex The regex
  169. *
  170. * @return string The converted regex
  171. */
  172. private function regexToApacheRegex($regex)
  173. {
  174. $regexPatternEnd = strrpos($regex, $regex[0]);
  175. return preg_replace('/\?P<.+?>/', '', substr($regex, 1, $regexPatternEnd - 1));
  176. }
  177. /**
  178. * Escapes a string.
  179. *
  180. * @param string $string The string to be escaped
  181. * @param string $char The character to be escaped
  182. * @param string $with The character to be used for escaping
  183. *
  184. * @return string The escaped string
  185. */
  186. private static function escape($string, $char, $with)
  187. {
  188. $escaped = false;
  189. $output = '';
  190. foreach (str_split($string) as $symbol) {
  191. if ($escaped) {
  192. $output .= $symbol;
  193. $escaped = false;
  194. continue;
  195. }
  196. if ($symbol === $char) {
  197. $output .= $with.$char;
  198. continue;
  199. }
  200. if ($symbol === $with) {
  201. $escaped = true;
  202. }
  203. $output .= $symbol;
  204. }
  205. return $output;
  206. }
  207. /**
  208. * Normalizes an array of values.
  209. *
  210. * @return string[]
  211. */
  212. private function normalizeValues(array $values)
  213. {
  214. $normalizedValues = array();
  215. foreach ($values as $key => $value) {
  216. if (\is_array($value)) {
  217. foreach ($value as $index => $bit) {
  218. $normalizedValues[sprintf('%s[%s]', $key, $index)] = $bit;
  219. }
  220. } else {
  221. $normalizedValues[$key] = (string) $value;
  222. }
  223. }
  224. return $normalizedValues;
  225. }
  226. }