4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Routing\Matcher\Dumper;
14 @trigger_error('The '.__NAMESPACE__.'\ApacheMatcherDumper class is deprecated since version 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);
16 use Symfony\Component\Routing\Route;
19 * Dumps a set of Apache mod_rewrite rules.
21 * @deprecated since version 2.5, to be removed in 3.0.
22 * The performance gains are minimal and it's very hard to replicate
23 * the behavior of PHP implementation.
25 * @author Fabien Potencier <fabien@symfony.com>
26 * @author Kris Wallsmith <kris@symfony.com>
28 class ApacheMatcherDumper extends MatcherDumper
31 * Dumps a set of Apache mod_rewrite rules.
35 * * script_name: The script name (app.php by default)
36 * * base_uri: The base URI ("" by default)
38 * @param array $options An array of options
40 * @return string A string to be used as Apache rewrite rules
42 * @throws \LogicException When the route regex is invalid
44 public function dump(array $options = array())
46 $options = array_merge(array(
47 'script_name' => 'app.php',
51 $options['script_name'] = self::escape($options['script_name'], ' ', '\\');
53 $rules = array("# skip \"real\" requests\nRewriteCond %{REQUEST_FILENAME} -f\nRewriteRule .* - [QSA,L]");
54 $methodVars = array();
58 foreach ($this->getRoutes()->all() as $name => $route) {
59 if ($route->getCondition()) {
60 throw new \LogicException(sprintf('Unable to dump the routes for Apache as route "%s" has a condition.', $name));
63 $compiledRoute = $route->compile();
64 $hostRegex = $compiledRoute->getHostRegex();
66 if (null !== $hostRegex && $prevHostRegex !== $hostRegex) {
67 $prevHostRegex = $hostRegex;
72 $regex = $this->regexToApacheRegex($hostRegex);
73 $regex = self::escape($regex, ' ', '\\');
75 $rule[] = sprintf('RewriteCond %%{HTTP:Host} %s', $regex);
78 $variables[] = sprintf('E=__ROUTING_host_%s:1', $hostRegexUnique);
80 foreach ($compiledRoute->getHostVariables() as $i => $variable) {
81 $variables[] = sprintf('E=__ROUTING_host_%s_%s:%%%d', $hostRegexUnique, $variable, $i + 1);
84 $variables = implode(',', $variables);
86 $rule[] = sprintf('RewriteRule .? - [%s]', $variables);
88 $rules[] = implode("\n", $rule);
91 $rules[] = $this->dumpRoute($name, $route, $options, $hostRegexUnique);
93 $methodVars = array_merge($methodVars, $route->getMethods());
95 if (0 < count($methodVars)) {
96 $rule = array('# 405 Method Not Allowed');
97 $methodVars = array_values(array_unique($methodVars));
98 if (in_array('GET', $methodVars) && !in_array('HEAD', $methodVars)) {
99 $methodVars[] = 'HEAD';
101 foreach ($methodVars as $i => $methodVar) {
102 $rule[] = sprintf('RewriteCond %%{ENV:_ROUTING__allow_%s} =1%s', $methodVar, isset($methodVars[$i + 1]) ? ' [OR]' : '');
104 $rule[] = sprintf('RewriteRule .* %s [QSA,L]', $options['script_name']);
106 $rules[] = implode("\n", $rule);
109 return implode("\n\n", $rules)."\n";
113 * Dumps a single route.
115 * @param string $name Route name
116 * @param Route $route The route
117 * @param array $options Options
118 * @param bool $hostRegexUnique Unique identifier for the host regex
120 * @return string The compiled route
122 private function dumpRoute($name, $route, array $options, $hostRegexUnique)
124 $compiledRoute = $route->compile();
126 // prepare the apache regex
127 $regex = $this->regexToApacheRegex($compiledRoute->getRegex());
128 $regex = '^'.self::escape(preg_quote($options['base_uri']).substr($regex, 1), ' ', '\\');
130 $methods = $this->getRouteMethods($route);
132 $hasTrailingSlash = (!$methods || in_array('HEAD', $methods)) && '/$' === substr($regex, -2) && '^/$' !== $regex;
134 $variables = array('E=_ROUTING_route:'.$name);
135 foreach ($compiledRoute->getHostVariables() as $variable) {
136 $variables[] = sprintf('E=_ROUTING_param_%s:%%{ENV:__ROUTING_host_%s_%s}', $variable, $hostRegexUnique, $variable);
138 foreach ($compiledRoute->getPathVariables() as $i => $variable) {
139 $variables[] = 'E=_ROUTING_param_'.$variable.':%'.($i + 1);
141 foreach ($this->normalizeValues($route->getDefaults()) as $key => $value) {
142 $variables[] = 'E=_ROUTING_default_'.$key.':'.strtr($value, array(
149 $variables = implode(',', $variables);
151 $rule = array("# $name");
154 if (0 < count($methods)) {
156 foreach ($methods as $method) {
157 $allow[] = 'E=_ROUTING_allow_'.$method.':1';
160 if ($compiledRoute->getHostRegex()) {
161 $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
164 $rule[] = "RewriteCond %{REQUEST_URI} $regex";
165 $rule[] = sprintf('RewriteCond %%{REQUEST_METHOD} !^(%s)$ [NC]', implode('|', $methods));
166 $rule[] = sprintf('RewriteRule .* - [S=%d,%s]', $hasTrailingSlash ? 2 : 1, implode(',', $allow));
169 // redirect with trailing slash appended
170 if ($hasTrailingSlash) {
171 if ($compiledRoute->getHostRegex()) {
172 $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
175 $rule[] = 'RewriteCond %{REQUEST_URI} '.substr($regex, 0, -2).'$';
176 $rule[] = 'RewriteRule .* $0/ [QSA,L,R=301]';
181 if ($compiledRoute->getHostRegex()) {
182 $rule[] = sprintf('RewriteCond %%{ENV:__ROUTING_host_%s} =1', $hostRegexUnique);
185 $rule[] = "RewriteCond %{REQUEST_URI} $regex";
186 $rule[] = "RewriteRule .* {$options['script_name']} [QSA,L,$variables]";
188 return implode("\n", $rule);
192 * Returns methods allowed for a route.
194 * @param Route $route The route
196 * @return array The methods
198 private function getRouteMethods(Route $route)
200 $methods = $route->getMethods();
202 // GET and HEAD are equivalent
203 if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
211 * Converts a regex to make it suitable for mod_rewrite.
213 * @param string $regex The regex
215 * @return string The converted regex
217 private function regexToApacheRegex($regex)
219 $regexPatternEnd = strrpos($regex, $regex[0]);
221 return preg_replace('/\?P<.+?>/', '', substr($regex, 1, $regexPatternEnd - 1));
227 * @param string $string The string to be escaped
228 * @param string $char The character to be escaped
229 * @param string $with The character to be used for escaping
231 * @return string The escaped string
233 private static function escape($string, $char, $with)
237 foreach (str_split($string) as $symbol) {
243 if ($symbol === $char) {
244 $output .= $with.$char;
247 if ($symbol === $with) {
257 * Normalizes an array of values.
259 * @param array $values
263 private function normalizeValues(array $values)
265 $normalizedValues = array();
266 foreach ($values as $key => $value) {
267 if (is_array($value)) {
268 foreach ($value as $index => $bit) {
269 $normalizedValues[sprintf('%s[%s]', $key, $index)] = $bit;
272 $normalizedValues[$key] = (string) $value;
276 return $normalizedValues;