PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/websocket/vendor/symfony/routing/Symfony/Component/Routing/Matcher/Dumper/ApacheMatcherDumper.php

https://github.com/ivebeenlinuxed/Boiler
PHP | 277 lines | 221 code | 17 blank | 39 comment | 5 complexity | c5f1fa04cbb07a028e79f7c442fc87ca 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. /**
  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. if ($route->getCondition()) {
  47. throw new \LogicException(sprintf('Unable to dump the routes for Apache as route "%s" has a condition.', $name));
  48. }
  49. $compiledRoute = $route->compile();
  50. $hostRegex = $compiledRoute->getHostRegex();
  51. if (null !== $hostRegex && $prevHostRegex !== $hostRegex) {
  52. $prevHostRegex = $hostRegex;
  53. $hostRegexUnique++;
  54. $rule = array();
  55. $regex = $this->regexToApacheRegex($hostRegex);
  56. $regex = self::escape($regex, ' ', '\\');
  57. $rule[] = sprintf('RewriteCond %%{HTTP:Host} %s', $regex);
  58. $variables = array();
  59. $variables[] = sprintf('E=__ROUTING_host_%s:1', $hostRegexUnique);
  60. foreach ($compiledRoute->getHostVariables() as $i => $variable) {
  61. $variables[] = sprintf('E=__ROUTING_host_%s_%s:%%%d', $hostRegexUnique, $variable, $i+1);
  62. }
  63. $variables = implode(',', $variables);
  64. $rule[] = sprintf('RewriteRule .? - [%s]', $variables);
  65. $rules[] = implode("\n", $rule);
  66. }
  67. $rules[] = $this->dumpRoute($name, $route, $options, $hostRegexUnique);
  68. if ($req = $route->getRequirement('_method')) {
  69. $methods = explode('|', strtoupper($req));
  70. $methodVars = array_merge($methodVars, $methods);
  71. }
  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. * @param Route $route The route
  155. *
  156. * @return array The methods
  157. */
  158. private function getRouteMethods(Route $route)
  159. {
  160. $methods = array();
  161. if ($req = $route->getRequirement('_method')) {
  162. $methods = explode('|', strtoupper($req));
  163. // GET and HEAD are equivalent
  164. if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
  165. $methods[] = 'HEAD';
  166. }
  167. }
  168. return $methods;
  169. }
  170. /**
  171. * Converts a regex to make it suitable for mod_rewrite
  172. *
  173. * @param string $regex The regex
  174. *
  175. * @return string The converted regex
  176. */
  177. private function regexToApacheRegex($regex)
  178. {
  179. $regexPatternEnd = strrpos($regex, $regex[0]);
  180. return preg_replace('/\?P<.+?>/', '', substr($regex, 1, $regexPatternEnd - 1));
  181. }
  182. /**
  183. * Escapes a string.
  184. *
  185. * @param string $string The string to be escaped
  186. * @param string $char The character to be escaped
  187. * @param string $with The character to be used for escaping
  188. *
  189. * @return string The escaped string
  190. */
  191. private static function escape($string, $char, $with)
  192. {
  193. $escaped = false;
  194. $output = '';
  195. foreach (str_split($string) as $symbol) {
  196. if ($escaped) {
  197. $output .= $symbol;
  198. $escaped = false;
  199. continue;
  200. }
  201. if ($symbol === $char) {
  202. $output .= $with.$char;
  203. continue;
  204. }
  205. if ($symbol === $with) {
  206. $escaped = true;
  207. }
  208. $output .= $symbol;
  209. }
  210. return $output;
  211. }
  212. /**
  213. * Normalizes an array of values.
  214. *
  215. * @param array $values
  216. *
  217. * @return string[]
  218. */
  219. private function normalizeValues(array $values)
  220. {
  221. $normalizedValues = array();
  222. foreach ($values as $key => $value) {
  223. if (is_array($value)) {
  224. foreach ($value as $index => $bit) {
  225. $normalizedValues[sprintf('%s[%s]', $key, $index)] = $bit;
  226. }
  227. } else {
  228. $normalizedValues[$key] = (string) $value;
  229. }
  230. }
  231. return $normalizedValues;
  232. }
  233. }