ApacheMatcherDumper.php 8.7 KB

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