Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

merged branch arnaud-lb/hostname-routes (PR #3378)

This PR was merged into the master branch.

Commits
-------

17f51a1 Merge pull request #6 from Tobion/hostname-routes
e120a7a fix API of RouteCollection
26e5684 some type fixes
514e27a [Routing] fix PhpMatcherDumper that returned numeric-indexed params that are returned besides named placeholders by preg_match
7ed3013 switch to array_replace instead of array_merge
94ec653 removed irrelevant string case in XmlFileLoader
9ffe3de synchronize the fixtures in different formats and fix default for numeric requirement
6cd3457 fixed CS
8366b8a [Routing] fixed validity check for hostname params in UrlGenerator
a8ce621 [Routing] added support for hostname in the apache matcher dumper
562174a [Routing] fixed indentation of dumped collections
1489021 fixed CS
a270458 [Routing] added some more unit tests
153fcf2 [Routing] added some unit tests for the PHP loader
68da6ad [Routing] added support for hostname in the XML loader
3dfca47 [Routing] added some unit tests for the YAML loader
92f9c15 [Routing] changed CompiledRoute signature to be more consistent
d91e5a2 [Routing] fixed Route annotation for hostname (should be hostname_pattern instead of hostnamePattern)
62de881 [Routing] clarified a variable content
11b4378 [Routing] added hostname support in UrlMatcher
fc015d5 [Routing] fixed route generation with a hostname pattern when the hostname is the same as the current one (no need to force the generated URL to be absolute)
462999d [Routing] display hostname pattern in router:debug output
805806a [Routing] added hostname matching support to UrlGenerator
7a15e00 [Routing] added hostname matching support to AnnotationClassLoader
cab450c [Routing] added hostname matching support to YamlFileLoader
85d11af [Routing] added hostname matching support to PhpMatcherDumper
402359b [Routing] added hostname matching support to RouteCompiler
add3658 [Routing] added hostname matching support to Route and RouteCollection
23feb37 [Routing] added hostname matching support to CompiledRoute

Discussion
----------

[2.2][Routing] hostname pattern for routes

Bug fix: no
Feature addition: yes
Fixes the following tickets: #1762, #3276
Backwards compatibility break: no
Symfony2 tests pass: yes

This adds a hostname_pattern property to routes. It works like the pattern property (hostname_pattern can have variables, requirements, etc). The hostname_pattern property can be set on both routes and route collections.

Yaml example:

``` yaml
# Setting the hostname_pattern for a whole collection of routes

AcmeBundle:
    resource: "@AcmeBundle/Controller/"
    type: annotation
    prefix: /
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr

# Setting the hostname_pattern for single route

some_route:
    pattern: /hello/{name}
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr
        name: \w+
    defaults:
        _controller: Foo:bar:baz
```

Annotations example:

``` php
<?php

/**
 * Inherits requirements and hostname pattern from the collection
 * @Route("/foo")
 */
public function fooAction();

/**
 * Set a specific hostnamePattern for this route only
 * @Route("/foo", hostnamePattern="{_locale}.example.com", requirements={"_locale="fr|en"})
 */
public function fooAction();

```

Performance:

Consecutive routes with the same hostname pattern are grouped, and a single test is made against the hostname for this group, so the overhead is very low:

```
@Route("/foo", hostnamePattern="a.example.com")
@Route("/bar", hostnamePattern="a.example.com")
@Route("/baz", hostnamePattern="b.example.com")
```

is compiled like this:

```
if (hostname matches a.example.com) {
    // test route "/foo"
    // test route "/bar"
}
if (hostname matches b.example.com) {
    // test route "/baz"
}
```

The PR also tries harder to optimize routes sharing the same prefix:

```
@Route("/cafe")
@Route("/cacao")
@Route("/coca")
```

is compiled like this:

```
if (url starts with /c) {
    if (url starts with /ca) {
        // test route "/cafe"
        // test route "/cacao"
    }
    // test route "/coca"
}
```

---------------------------------------------------------------------------

by Koc at 2012-02-16T14:14:19Z

Interesting. Have you looked at #3057, #3002?

Killer feature of #3057 : multiple hostnames per route.

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T14:21:28Z

@Koc yes, the main difference is that this PR allows variables in the hostname pattern, with requirements, etc just like the path pattern. The other PRs use a `_host` requirement, which works like the `_method` requirement (takes a list of allowed hostnames separated by `|`).

> Killer feature of #3057 : multiple hostnames per route.

If you have multiple tlds you can easily do it like this:

``` yaml
hostbased_route:
  pattern:  /
  hostname_pattern: symfony.{tld}
  requirements:
     tld: org|com
```

Or with completely different domain names:

``` yaml
hostbased_route:
  pattern:  /
  hostname_pattern: {domain}
  requirements:
     domain: example\.com|symfony\.com
```

Requirements allow DIC %parameters%, so you can also put you domains in your config.yml.

---------------------------------------------------------------------------

by Koc at 2012-02-16T15:52:16Z

wow, nice! So looks like this PR closes my #3276 ticket?

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T15:53:55Z

Yes, apparently :)

---------------------------------------------------------------------------

by Koc at 2012-02-16T15:56:53Z

I cann't find method `ParameterBag::resolveValue` calling in this PR, like here https://github.com/symfony/symfony/pull/3316/files

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T16:03:48Z

I think it's in core already

---------------------------------------------------------------------------

by Koc at 2012-02-16T16:11:38Z

looks like yes
https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php#L81

---------------------------------------------------------------------------

by dlsniper at 2012-02-16T19:37:57Z

This PR looks great, it's something like this I've been waiting for.

I know @fabpot said he's working on something similar but I think if he agrees with this it could be a great addition to the core.

@fabpot , @stof any objections about this PR if gets fully done?

---------------------------------------------------------------------------

by stof at 2012-02-16T20:00:21Z

Well, we already have 2 other implementations for this stuff in the PRs. @fabpot please take time to look at them

---------------------------------------------------------------------------

by stof at 2012-02-16T20:03:17Z

This one is absolutely not tested and seems to break the existing tests according to the description. So it cannot be reviewed as is.

---------------------------------------------------------------------------

by dlsniper at 2012-02-16T22:00:24Z

@stof I understand it's a WIP but the other PRs where ignored as well and like you've said, there's a bunch of PRs already on this issue all doing a thing or another. So an early feedback on this, or any other, could lead it to the right path in order to finally solve this issue.

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-17T23:57:28Z

Added tests; others are passing now

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-22T21:10:20Z

I'm going to add support for the Apache dumper and the XML loader; does this PR have a chance to be merged ? cc @fabpot @stof

---------------------------------------------------------------------------

by stof at 2012-02-22T22:05:23Z

@arnaud-lb We need to wait @fabpot's mind about the way he prefers to implement it to know which one can be merged.

---------------------------------------------------------------------------

by IjinPL at 2012-02-27T02:01:57Z

Forked @arnaud-lb *hostname_pattern* to add XML parasing support.

---------------------------------------------------------------------------

by stof at 2012-04-03T23:59:12Z

@arnaud-lb Please rebase your branch. It conflicts with master because of the move of the tests

@fabpot @vicb ping

---------------------------------------------------------------------------

by dlsniper at 2012-04-13T19:52:23Z

Hi,

If @arnaud-lb won't be able to rebase this I could help with some work on this but there's still the problem of actually choosing the right PR(s) for this issue. @blogsh says in his last commit that this PR is a bit better in his opinion but @fabpot needs to decide in the end.

---------------------------------------------------------------------------

by arnaud-lb at 2012-04-14T17:26:55Z

@stof rebased

---------------------------------------------------------------------------

by nomack84 at 2012-04-20T13:01:00Z

@fabpot Any final word about this pull request? It would be nice to have this feature ready for 2.1.

---------------------------------------------------------------------------

by asm89 at 2012-04-24T21:27:50Z

Using the `{_locale}` placeholder in the host would set the locale for the request just like it does now?

Another thing I'm wondering is how/if it should be possible to set the hostname pattern for all your routes, or at least when importing routes? Otherwise you'll end up repeating the same host pattern over and over again. I think this is also important when importing routes from third party bundles.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T01:17:51Z

I'm reviewing this PR and I'm going to make some modifications. I will send a PR to @arnaud-lb soon.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T03:10:18Z

I've sent a PR to @arnaud-lb arnaud-lb/symfony#3 that fixes some minor bugs and add support in more classes.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T03:12:52Z

@asm89:

Placeholders in the hostname are managed in the same way as the ones from the URL pattern.

You can set a hostname pattern for a collection (like the prefix for URL patterns).

---------------------------------------------------------------------------

by Tobion at 2012-04-25T09:31:19Z

I think we need to change the contents of $variables, $tokens, and $hostnameTokens in the CompiledRoute. They contain redundant information and the content structure of these variables ist not documentation in any way. If we remove duplicated content and put it in a (single) well defined variable, it would also reduce the information that need to be saved in the generated class by the UrlGeneratorDumper.

---------------------------------------------------------------------------

by arnaud-lb at 2012-04-26T08:54:21Z

@fabpot thanks :) I've merged it

---------------------------------------------------------------------------

by stof at 2012-04-26T12:08:40Z

A rebase is needed

---------------------------------------------------------------------------

by fabpot at 2012-04-26T13:28:08Z

no need to rebase, I will resolve the conflicts when merging. I've still have some minor changes to do before merging though. Anyone willing to have a look at implementing the Apache dumper part?

---------------------------------------------------------------------------

by Tobion at 2012-04-26T14:59:00Z

@fabpot you want to merge this for 2.1 although it introduces big changes that need extensive review and testing? But #3958 is not considered for 2.1? I thought we are in some sort of feature freeze for the components in order to not postpone the release.

---------------------------------------------------------------------------

by fabpot at 2012-04-26T17:21:09Z

@Tobion: I never said it will be in 2.1. The plan is to create a 2.1 branch soon so that we can continue working on 2.2.

---------------------------------------------------------------------------

by Koc at 2012-04-26T19:46:43Z

https://twitter.com/#!/fabpot/status/178502663690915840
  • Loading branch information...
commit c94bdf6bdfefd3e81049a218bb3c2f7e6c2b941f 2 parents f4c05e3 + 17f51a1
@fabpot fabpot authored
Showing with 1,210 additions and 239 deletions.
  1. +15 −14 src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php
  2. +12 −1 src/Symfony/Component/Routing/Annotation/Route.php
  3. +59 −6 src/Symfony/Component/Routing/CompiledRoute.php
  4. +3 −2 src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
  5. +34 −4 src/Symfony/Component/Routing/Generator/UrlGenerator.php
  6. +19 −9 src/Symfony/Component/Routing/Loader/AnnotationClassLoader.php
  7. +13 −12 src/Symfony/Component/Routing/Loader/XmlFileLoader.php
  8. +5 −3 src/Symfony/Component/Routing/Loader/YamlFileLoader.php
  9. +2 −0  src/Symfony/Component/Routing/Loader/schema/routing/routing-1.0.xsd
  10. +71 −7 src/Symfony/Component/Routing/Matcher/Dumper/ApacheMatcherDumper.php
  11. +48 −1 src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php
  12. +86 −19 src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
  13. +6 −1 src/Symfony/Component/Routing/Matcher/UrlMatcher.php
  14. +26 −1 src/Symfony/Component/Routing/Route.php
  15. +38 −6 src/Symfony/Component/Routing/RouteCollection.php
  16. +64 −12 src/Symfony/Component/Routing/RouteCompiler.php
  17. +2 −1  src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php
  18. +5 −5 src/Symfony/Component/Routing/Tests/CompiledRouteTest.php
  19. +91 −3 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.apache
  20. +114 −55 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.php
  21. +114 −55 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.php
  22. +1 −3 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher3.php
  23. +3 −2 src/Symfony/Component/Routing/Tests/Fixtures/validpattern.php
  24. +2 −1  src/Symfony/Component/Routing/Tests/Fixtures/validpattern.xml
  25. +4 −2 src/Symfony/Component/Routing/Tests/Fixtures/validpattern.yml
  26. +2 −2 src/Symfony/Component/Routing/Tests/Fixtures/validresource.xml
  27. +6 −5 src/Symfony/Component/Routing/Tests/Fixtures/validresource.yml
  28. +58 −2 src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php
  29. +4 −0 src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php
  30. +9 −1 src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php
  31. +9 −1 src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php
  32. +14 −0 src/Symfony/Component/Routing/Tests/Matcher/ApacheUrlMatcherTest.php
  33. +65 −0 src/Symfony/Component/Routing/Tests/Matcher/Dumper/ApacheMatcherDumperTest.php
  34. +24 −0 src/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperCollectionTest.php
  35. +0 −1  src/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperPrefixCollectionTest.php
  36. +53 −1 src/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php
  37. +35 −0 src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php
  38. +14 −0 src/Symfony/Component/Routing/Tests/RouteCollectionTest.php
  39. +71 −0 src/Symfony/Component/Routing/Tests/RouteCompilerTest.php
  40. +9 −1 src/Symfony/Component/Routing/Tests/RouteTest.php
View
29 src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php
@@ -15,7 +15,6 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\RouterInterface;
-use Symfony\Component\Console\Output\Output;
/**
* A console command for retrieving information about routes
@@ -82,8 +81,10 @@ protected function outputRoutes(OutputInterface $output, $routes = null)
$output->writeln($this->getHelper('formatter')->formatSection('router', 'Current routes'));
- $maxName = 4;
- $maxMethod = 6;
+ $maxName = strlen('name');
+ $maxMethod = strlen('method');
+ $maxHostname = strlen('hostname');
+
foreach ($routes as $name => $route) {
$requirements = $route->getRequirements();
$method = isset($requirements['_method'])
@@ -91,20 +92,18 @@ protected function outputRoutes(OutputInterface $output, $routes = null)
? implode(', ', $requirements['_method']) : $requirements['_method']
)
: 'ANY';
+ $hostname = '' !== $route->getHostnamePattern()
+ ? $route->getHostnamePattern() : 'ANY';
- if (strlen($name) > $maxName) {
- $maxName = strlen($name);
- }
-
- if (strlen($method) > $maxMethod) {
- $maxMethod = strlen($method);
- }
+ $maxName = max($maxName, strlen($name));
+ $maxMethod = max($maxMethod, strlen($method));
+ $maxHostname = max($maxHostname, strlen($hostname));
}
- $format = '%-'.$maxName.'s %-'.$maxMethod.'s %s';
+ $format = '%-'.$maxName.'s %-'.$maxMethod.'s %-'.$maxHostname.'s %s';
// displays the generated routes
- $format1 = '%-'.($maxName + 19).'s %-'.($maxMethod + 19).'s %s';
- $output->writeln(sprintf($format1, '<comment>Name</comment>', '<comment>Method</comment>', '<comment>Pattern</comment>'));
+ $format1 = '%-'.($maxName + 19).'s %-'.($maxMethod + 19).'s %-'.($maxHostname + 19).'s %s';
+ $output->writeln(sprintf($format1, '<comment>Name</comment>', '<comment>Method</comment>', '<comment>Hostname</comment>', '<comment>Pattern</comment>'));
foreach ($routes as $name => $route) {
$requirements = $route->getRequirements();
$method = isset($requirements['_method'])
@@ -112,7 +111,9 @@ protected function outputRoutes(OutputInterface $output, $routes = null)
? implode(', ', $requirements['_method']) : $requirements['_method']
)
: 'ANY';
- $output->writeln(sprintf($format, $name, $method, $route->getPattern()));
+ $hostname = '' !== $route->getHostnamePattern()
+ ? $route->getHostnamePattern() : 'ANY';
+ $output->writeln(sprintf($format, $name, $method, $hostname, $route->getPattern()));
}
}
View
13 src/Symfony/Component/Routing/Annotation/Route.php
@@ -25,6 +25,7 @@ class Route
private $requirements;
private $options;
private $defaults;
+ private $hostnamePattern;
/**
* Constructor.
@@ -43,7 +44,7 @@ public function __construct(array $data)
}
foreach ($data as $key => $value) {
- $method = 'set'.$key;
+ $method = 'set'.str_replace('_', '', $key);
if (!method_exists($this, $method)) {
throw new \BadMethodCallException(sprintf("Unknown property '%s' on annotation '%s'.", $key, get_class($this)));
}
@@ -61,6 +62,16 @@ public function getPattern()
return $this->pattern;
}
+ public function setHostnamePattern($pattern)
+ {
+ $this->hostnamePattern = $pattern;
+ }
+
+ public function getHostnamePattern()
+ {
+ return $this->hostnamePattern;
+ }
+
public function setName($name)
{
$this->name = $name;
View
65 src/Symfony/Component/Routing/CompiledRoute.php
@@ -22,20 +22,32 @@ class CompiledRoute
private $tokens;
private $staticPrefix;
private $regex;
+ private $pathVariables;
+ private $hostnameVariables;
+ private $hostnameRegex;
+ private $hostnameTokens;
/**
* Constructor.
*
- * @param string $staticPrefix The static prefix of the compiled route
- * @param string $regex The regular expression to use to match this route
- * @param array $tokens An array of tokens to use to generate URL for this route
- * @param array $variables An array of variables
+ * @param string $staticPrefix The static prefix of the compiled route
+ * @param string $regex The regular expression to use to match this route
+ * @param array $tokens An array of tokens to use to generate URL for this route
+ * @param array $pathVariables An array of path variables
+ * @param string|null $hostnameRegex Hostname regex
+ * @param array $hostnameTokens Hostname tokens
+ * @param array $hostnameVariables An array of hostname variables
+ * @param array $variables An array of variables (variables defined in the path and in the hostname patterns)
*/
- public function __construct($staticPrefix, $regex, array $tokens, array $variables)
+ public function __construct($staticPrefix, $regex, array $tokens, array $pathVariables, $hostnameRegex = null, array $hostnameTokens = array(), array $hostnameVariables = array(), array $variables = array())
{
- $this->staticPrefix = $staticPrefix;
+ $this->staticPrefix = (string) $staticPrefix;
$this->regex = $regex;
$this->tokens = $tokens;
+ $this->pathVariables = $pathVariables;
+ $this->hostnameRegex = $hostnameRegex;
+ $this->hostnameTokens = $hostnameTokens;
+ $this->hostnameVariables = $hostnameVariables;
$this->variables = $variables;
}
@@ -60,6 +72,16 @@ public function getRegex()
}
/**
+ * Returns the hostname regex
+ *
+ * @return string|null The hostname regex or null
+ */
+ public function getHostnameRegex()
+ {
+ return $this->hostnameRegex;
+ }
+
+ /**
* Returns the tokens.
*
* @return array The tokens
@@ -70,6 +92,16 @@ public function getTokens()
}
/**
+ * Returns the hostname tokens.
+ *
+ * @return array The tokens
+ */
+ public function getHostnameTokens()
+ {
+ return $this->hostnameTokens;
+ }
+
+ /**
* Returns the variables.
*
* @return array The variables
@@ -78,4 +110,25 @@ public function getVariables()
{
return $this->variables;
}
+
+ /**
+ * Returns the path variables.
+ *
+ * @return array The variables
+ */
+ public function getPathVariables()
+ {
+ return $this->pathVariables;
+ }
+
+ /**
+ * Returns the hostname variables.
+ *
+ * @return array The variables
+ */
+ public function getHostnameVariables()
+ {
+ return $this->hostnameVariables;
+ }
+
}
View
5 src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
@@ -91,6 +91,7 @@ private function generateDeclaredRoutes()
$properties[] = $route->getDefaults();
$properties[] = $route->getRequirements();
$properties[] = $compiledRoute->getTokens();
+ $properties[] = $compiledRoute->getHostnameTokens();
$routes .= sprintf(" '%s' => %s,\n", $name, str_replace("\n", '', var_export($properties, true)));
}
@@ -113,9 +114,9 @@ public function generate(\$name, \$parameters = array(), \$absolute = false)
throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', \$name));
}
- list(\$variables, \$defaults, \$requirements, \$tokens) = self::\$declaredRoutes[\$name];
+ list(\$variables, \$defaults, \$requirements, \$tokens, \$hostnameTokens) = self::\$declaredRoutes[\$name];
- return \$this->doGenerate(\$variables, \$defaults, \$requirements, \$tokens, \$parameters, \$name, \$absolute);
+ return \$this->doGenerate(\$variables, \$defaults, \$requirements, \$tokens, \$parameters, \$name, \$absolute, \$hostnameTokens);
}
EOF;
}
View
38 src/Symfony/Component/Routing/Generator/UrlGenerator.php
@@ -122,14 +122,14 @@ public function generate($name, $parameters = array(), $absolute = false)
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
- return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $absolute);
+ return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $absolute, $compiledRoute->getHostnameTokens());
}
/**
* @throws MissingMandatoryParametersException When route has some missing mandatory parameters
* @throws InvalidParameterException When a parameter value is not correct
*/
- protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
+ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute, $hostnameTokens)
{
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
@@ -191,13 +191,43 @@ protected function doGenerate($variables, $defaults, $requirements, $tokens, $pa
$url .= '?'.$query;
}
- if ($this->context->getHost()) {
+ if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) {
$absolute = true;
$scheme = $req;
}
+ if ($hostnameTokens) {
+ $routeHost = '';
+ foreach ($hostnameTokens as $token) {
+ if ('variable' === $token[0]) {
+ if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
+ $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $mergedParams[$token[3]]);
+
+ if ($this->strictRequirements) {
+ throw new InvalidParameterException($message);
+ }
+
+ if ($this->logger) {
+ $this->logger->err($message);
+ }
+
+ return null;
+ }
+
+ $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
+ } elseif ('text' === $token[0]) {
+ $routeHost = $token[1].$routeHost;
+ }
+ }
+
+ if ($routeHost != $host) {
+ $host = $routeHost;
+ $absolute = true;
+ }
+ }
+
if ($absolute) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
@@ -206,7 +236,7 @@ protected function doGenerate($variables, $defaults, $requirements, $tokens, $pa
$port = ':'.$this->context->getHttpsPort();
}
- $url = $scheme.'://'.$this->context->getHost().$port.$url;
+ $url = $scheme.'://'.$host.$port.$url;
}
}
View
28 src/Symfony/Component/Routing/Loader/AnnotationClassLoader.php
@@ -57,7 +57,7 @@
abstract class AnnotationClassLoader implements LoaderInterface
{
protected $reader;
- protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
+ protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
protected $defaultRouteIndex;
/**
@@ -97,10 +97,11 @@ public function load($class, $type = null)
}
$globals = array(
- 'pattern' => '',
- 'requirements' => array(),
- 'options' => array(),
- 'defaults' => array(),
+ 'pattern' => '',
+ 'requirements' => array(),
+ 'options' => array(),
+ 'defaults' => array(),
+ 'hostname_pattern' => '',
);
$class = new \ReflectionClass($class);
@@ -124,6 +125,10 @@ public function load($class, $type = null)
if (null !== $annot->getDefaults()) {
$globals['defaults'] = $annot->getDefaults();
}
+
+ if (null !== $annot->getHostnamePattern()) {
+ $globals['hostname_pattern'] = $annot->getHostnamePattern();
+ }
}
$collection = new RouteCollection();
@@ -148,16 +153,21 @@ protected function addRoute(RouteCollection $collection, $annot, $globals, \Refl
$name = $this->getDefaultRouteName($class, $method);
}
- $defaults = array_merge($globals['defaults'], $annot->getDefaults());
+ $defaults = array_replace($globals['defaults'], $annot->getDefaults());
foreach ($method->getParameters() as $param) {
if ($param->isOptional()) {
$defaults[$param->getName()] = $param->getDefaultValue();
}
}
- $requirements = array_merge($globals['requirements'], $annot->getRequirements());
- $options = array_merge($globals['options'], $annot->getOptions());
+ $requirements = array_replace($globals['requirements'], $annot->getRequirements());
+ $options = array_replace($globals['options'], $annot->getOptions());
+
+ $hostnamePattern = $annot->getHostnamePattern();
+ if (null === $hostnamePattern) {
+ $hostnamePattern = $globals['hostname_pattern'];
+ }
- $route = new Route($globals['pattern'].$annot->getPattern(), $defaults, $requirements, $options);
+ $route = new Route($globals['pattern'].$annot->getPattern(), $defaults, $requirements, $options, $hostnamePattern);
$this->configureRoute($route, $class, $method, $annot);
View
25 src/Symfony/Component/Routing/Loader/XmlFileLoader.php
@@ -73,9 +73,10 @@ protected function parseNode(RouteCollection $collection, \DOMElement $node, $pa
$this->parseRoute($collection, $node, $path);
break;
case 'import':
- $resource = (string) $node->getAttribute('resource');
- $type = (string) $node->getAttribute('type');
- $prefix = (string) $node->getAttribute('prefix');
+ $resource = $node->getAttribute('resource');
+ $type = $node->getAttribute('type');
+ $prefix = $node->getAttribute('prefix');
+ $hostnamePattern = $node->getAttribute('hostname-pattern');
$defaults = array();
$requirements = array();
@@ -88,13 +89,13 @@ protected function parseNode(RouteCollection $collection, \DOMElement $node, $pa
switch ($n->tagName) {
case 'default':
- $defaults[(string) $n->getAttribute('key')] = trim((string) $n->nodeValue);
+ $defaults[$n->getAttribute('key')] = trim($n->nodeValue);
break;
case 'requirement':
- $requirements[(string) $n->getAttribute('key')] = trim((string) $n->nodeValue);
+ $requirements[$n->getAttribute('key')] = trim($n->nodeValue);
break;
case 'option':
- $options[(string) $n->getAttribute('key')] = trim((string) $n->nodeValue);
+ $options[$n->getAttribute('key')] = trim($n->nodeValue);
break;
default:
throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $n->tagName));
@@ -102,7 +103,7 @@ protected function parseNode(RouteCollection $collection, \DOMElement $node, $pa
}
$this->setCurrentDir(dirname($path));
- $collection->addCollection($this->import($resource, ('' !== $type ? $type : null), false, $file), $prefix, $defaults, $requirements, $options);
+ $collection->addCollection($this->import($resource, ('' !== $type ? $type : null), false, $file), $prefix, $defaults, $requirements, $options, $hostnamePattern);
break;
default:
throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
@@ -141,22 +142,22 @@ protected function parseRoute(RouteCollection $collection, \DOMElement $definiti
switch ($node->tagName) {
case 'default':
- $defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
+ $defaults[$node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
case 'option':
- $options[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
+ $options[$node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
case 'requirement':
- $requirements[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
+ $requirements[$node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
default:
throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
}
}
- $route = new Route((string) $definition->getAttribute('pattern'), $defaults, $requirements, $options);
+ $route = new Route($definition->getAttribute('pattern'), $defaults, $requirements, $options, $definition->getAttribute('hostname-pattern'));
- $collection->add((string) $definition->getAttribute('id'), $route);
+ $collection->add($definition->getAttribute('id'), $route);
}
/**
View
8 src/Symfony/Component/Routing/Loader/YamlFileLoader.php
@@ -27,7 +27,7 @@
class YamlFileLoader extends FileLoader
{
private static $availableKeys = array(
- 'type', 'resource', 'prefix', 'pattern', 'options', 'defaults', 'requirements'
+ 'type', 'resource', 'prefix', 'pattern', 'options', 'defaults', 'requirements', 'hostname_pattern',
);
/**
@@ -70,9 +70,10 @@ public function load($file, $type = null)
$defaults = isset($config['defaults']) ? $config['defaults'] : array();
$requirements = isset($config['requirements']) ? $config['requirements'] : array();
$options = isset($config['options']) ? $config['options'] : array();
+ $hostnamePattern = isset($config['hostname_pattern']) ? $config['hostname_pattern'] : '';
$this->setCurrentDir(dirname($path));
- $collection->addCollection($this->import($config['resource'], $type, false, $file), $prefix, $defaults, $requirements, $options);
+ $collection->addCollection($this->import($config['resource'], $type, false, $file), $prefix, $defaults, $requirements, $options, $hostnamePattern);
} else {
$this->parseRoute($collection, $name, $config, $path);
}
@@ -106,12 +107,13 @@ protected function parseRoute(RouteCollection $collection, $name, $config, $file
$defaults = isset($config['defaults']) ? $config['defaults'] : array();
$requirements = isset($config['requirements']) ? $config['requirements'] : array();
$options = isset($config['options']) ? $config['options'] : array();
+ $hostnamePattern = isset($config['hostname_pattern']) ? $config['hostname_pattern'] : null;
if (!isset($config['pattern'])) {
throw new \InvalidArgumentException(sprintf('You must define a "pattern" for the "%s" route.', $name));
}
- $route = new Route($config['pattern'], $defaults, $requirements, $options);
+ $route = new Route($config['pattern'], $defaults, $requirements, $options, $hostnamePattern);
$collection->add($name, $route);
}
View
2  src/Symfony/Component/Routing/Loader/schema/routing/routing-1.0.xsd
@@ -23,6 +23,7 @@
<xsd:attribute name="id" type="xsd:string" />
<xsd:attribute name="pattern" type="xsd:string" />
+ <xsd:attribute name="hostname-pattern" type="xsd:string" />
</xsd:complexType>
<xsd:complexType name="import">
@@ -36,6 +37,7 @@
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="prefix" type="xsd:string" />
<xsd:attribute name="class" type="xsd:string" />
+ <xsd:attribute name="hostname-pattern" type="xsd:string" />
</xsd:complexType>
<xsd:complexType name="element" mixed="true">
View
78 src/Symfony/Component/Routing/Matcher/Dumper/ApacheMatcherDumper.php
@@ -46,17 +46,55 @@ public function dump(array $options = array())
$rules = array("# skip \"real\" requests\nRewriteCond %{REQUEST_FILENAME} -f\nRewriteRule .* - [QSA,L]");
$methodVars = array();
+ $hostnameRegexUnique = 0;
+ $prevHosnameRegex = '';
foreach ($this->getRoutes()->all() as $name => $route) {
- $rules[] = $this->dumpRoute($name, $route, $options);
- $methodVars = array_merge($methodVars, $this->getRouteMethods($route));
- }
+ $compiledRoute = $route->compile();
+ $hostnameRegex = $compiledRoute->getHostnameRegex();
+
+ if (null !== $hostnameRegex && $prevHosnameRegex !== $hostnameRegex) {
+
+ $prevHosnameRegex = $hostnameRegex;
+ $hostnameRegexUnique++;
+
+ $rule = array();
+
+ $regex = $this->regexToApacheRegex($hostnameRegex);
+ $regex = self::escape($regex, ' ', '\\');
+
+ $rule[] = sprintf('RewriteCond %%{HTTP:Host} %s', $regex);
+
+ $variables = array();
+ $variables[] = sprintf('E=__ROUTING_hostname_%s:1', $hostnameRegexUnique);
+
+ foreach ($compiledRoute->getHostnameVariables() as $i => $variable) {
+ $variables[] = sprintf('E=__ROUTING_hostname_%s_%s:%%%d', $hostnameRegexUnique, $variable, $i+1);
+ }
+
+ $variables = implode(',', $variables);
+
+ $rule[] = sprintf('RewriteRule .? - [%s]', $variables);
+
+ $rules[] = implode("\n", $rule);
+ }
+
+ $rules[] = $this->dumpRoute($name, $route, $options, $hostnameRegexUnique);
+
+ if ($req = $route->getRequirement('_method')) {
+ $methods = explode('|', strtoupper($req));
+ $methodVars = array_merge($methodVars, $methods);
+ }
+ }
if (0 < count($methodVars)) {
$rule = array('# 405 Method Not Allowed');
$methodVars = array_values(array_unique($methodVars));
+ if (in_array('GET', $methodVars) && !in_array('HEAD', $methodVars)) {
+ $methodVars[] = 'HEAD';
+ }
foreach ($methodVars as $i => $methodVar) {
- $rule[] = sprintf('RewriteCond %%{_ROUTING_allow_%s} !-z%s', $methodVar, isset($methodVars[$i + 1]) ? ' [OR]' : '');
+ $rule[] = sprintf('RewriteCond %%{ENV:_ROUTING__allow_%s} =1%s', $methodVar, isset($methodVars[$i + 1]) ? ' [OR]' : '');
}
$rule[] = sprintf('RewriteRule .* %s [QSA,L]', $options['script_name']);
@@ -66,7 +104,17 @@ public function dump(array $options = array())
return implode("\n\n", $rules)."\n";
}
- private function dumpRoute($name, $route, array $options)
+ /**
+ * Dumps a single route
+ *
+ * @param string $name Route name
+ * @param Route $route The route
+ * @param array $options Options
+ * @param bool $hostnameRegexUnique Unique identifier for the hostname regex
+ *
+ * @return string The compiled route
+ */
+ private function dumpRoute($name, $route, array $options, $hostnameRegexUnique)
{
$compiledRoute = $route->compile();
@@ -79,7 +127,10 @@ private function dumpRoute($name, $route, array $options)
$hasTrailingSlash = (!$methods || in_array('HEAD', $methods)) && '/$' === substr($regex, -2) && '^/$' !== $regex;
$variables = array('E=_ROUTING_route:'.$name);
- foreach ($compiledRoute->getVariables() as $i => $variable) {
+ foreach ($compiledRoute->getHostnameVariables() as $variable) {
+ $variables[] = sprintf('E=_ROUTING_param_%s:%%{ENV:__ROUTING_hostname_%s_%s}', $variable, $hostnameRegexUnique, $variable);
+ }
+ foreach ($compiledRoute->getPathVariables() as $i => $variable) {
$variables[] = 'E=_ROUTING_param_'.$variable.':%'.($i + 1);
}
foreach ($route->getDefaults() as $key => $value) {
@@ -98,10 +149,13 @@ private function dumpRoute($name, $route, array $options)
if (0 < count($methods)) {
$allow = array();
foreach ($methods as $method) {
- $methodVars[] = $method;
$allow[] = 'E=_ROUTING_allow_'.$method.':1';
}
+ if ($hostnameRegex = $compiledRoute->getHostnameRegex()) {
+ $rule[] = sprintf("RewriteCond %%{ENV:__ROUTING_hostname_%s} =1", $hostnameRegexUnique);
+ }
+
$rule[] = "RewriteCond %{REQUEST_URI} $regex";
$rule[] = sprintf("RewriteCond %%{REQUEST_METHOD} !^(%s)$ [NC]", implode('|', $methods));
$rule[] = sprintf('RewriteRule .* - [S=%d,%s]', $hasTrailingSlash ? 2 : 1, implode(',', $allow));
@@ -109,11 +163,21 @@ private function dumpRoute($name, $route, array $options)
// redirect with trailing slash appended
if ($hasTrailingSlash) {
+
+ if ($hostnameRegex = $compiledRoute->getHostnameRegex()) {
+ $rule[] = sprintf("RewriteCond %%{ENV:__ROUTING_hostname_%s} =1", $hostnameRegexUnique);
+ }
+
$rule[] = 'RewriteCond %{REQUEST_URI} '.substr($regex, 0, -2).'$';
$rule[] = 'RewriteRule .* $0/ [QSA,L,R=301]';
}
// the main rule
+
+ if ($hostnameRegex = $compiledRoute->getHostnameRegex()) {
+ $rule[] = sprintf("RewriteCond %%{ENV:__ROUTING_hostname_%s} =1", $hostnameRegexUnique);
+ }
+
$rule[] = "RewriteCond %{REQUEST_URI} $regex";
$rule[] = "RewriteRule .* {$options['script_name']} [QSA,L,$variables]";
View
49 src/Symfony/Component/Routing/Matcher/Dumper/DumperCollection.php
@@ -20,6 +20,7 @@ class DumperCollection implements \IteratorAggregate
{
private $parent;
private $children = array();
+ private $attributes = array();
/**
* Returns the children routes and collections.
@@ -45,7 +46,7 @@ public function add($child)
}
/**
- * Sets children
+ * Sets children.
*
* @param array $children The children
*/
@@ -98,4 +99,50 @@ protected function setParent(DumperCollection $parent)
{
$this->parent = $parent;
}
+
+ /**
+ * Returns true if the attribute is defined.
+ *
+ * @param string $name The attribute name
+ *
+ * @return Boolean true if the attribute is defined, false otherwise
+ */
+ public function hasAttribute($name)
+ {
+ return array_key_exists($name, $this->attributes);
+ }
+
+ /**
+ * Returns an attribute by name.
+ *
+ * @param string $name The attribute name
+ * @param mixed $default Default value is the attribute doesn't exist
+ *
+ * @return mixed The attribute value
+ */
+ public function getAttribute($name, $default = null)
+ {
+ return $this->hasAttribute($name) ? $this->attributes[$name] : $default;
+ }
+
+ /**
+ * Sets an attribute by name.
+ *
+ * @param string $name The attribute name
+ * @param mixed $value The attribute value
+ */
+ public function setAttribute($name, $value)
+ {
+ $this->attributes[$name] = $value;
+ }
+
+ /**
+ * Sets multiple attributes.
+ *
+ * @param array $attributes The attributes
+ */
+ public function setAttributes($attributes)
+ {
+ $this->attributes = $attributes;
+ }
}
View
105 src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php
@@ -37,7 +37,7 @@ class PhpMatcherDumper extends MatcherDumper
*/
public function dump(array $options = array())
{
- $options = array_merge(array(
+ $options = array_replace(array(
'class' => 'ProjectUrlMatcher',
'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
), $options);
@@ -109,18 +109,44 @@ public function match(\$pathinfo)
*/
private function compileRoutes(RouteCollection $routes, $supportsRedirections)
{
- $collection = $this->flattenRouteCollection($routes);
- $tree = $this->buildPrefixTree($collection);
+ $fetchedHostname = false;
- return $this->compilePrefixRoutes($tree, $supportsRedirections);
+ $routes = $this->flattenRouteCollection($routes);
+ $groups = $this->groupRoutesByHostnameRegex($routes);
+ $code = '';
+
+ foreach ($groups as $collection) {
+ if (null !== $regex = $collection->getAttribute('hostname_regex')) {
+ if (!$fetchedHostname) {
+ $code .= " \$hostname = \$this->context->getHost();\n\n";
+ $fetchedHostname = true;
+ }
+
+ $code .= sprintf(" if (preg_match(%s, \$hostname, \$hostnameMatches)) {\n", var_export($regex, true));
+ }
+
+ $tree = $this->buildPrefixTree($collection);
+ $groupCode = $this->compilePrefixRoutes($tree, $supportsRedirections);
+
+ if (null !== $regex) {
+ // apply extra indention at each line (except empty ones)
+ $groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
+ $code .= $groupCode;
+ $code .= " }\n\n";
+ } else {
+ $code .= $groupCode;
+ }
+ }
+
+ return $code;
}
/**
* Generates PHP code recursively to match a tree of routes
*
- * @param DumperPrefixCollection $routes A DumperPrefixCollection instance
+ * @param DumperPrefixCollection $routes A DumperPrefixCollection instance
* @param Boolean $supportsRedirections Whether redirections are supported by the base class
- * @parma string $prefix Prefix of the parent collection
+ * @parma string $prefix Prefix of the parent collection
*
* @return string PHP code
*/
@@ -171,6 +197,7 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren
$conditions = array();
$hasTrailingSlash = false;
$matches = false;
+ $hostnameMatches = false;
$methods = array();
if ($req = $route->getRequirement('_method')) {
@@ -183,7 +210,7 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren
$supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
- if (!count($compiledRoute->getVariables()) && false !== preg_match('#^(.)\^(?<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
+ if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?<url>.*?)\$\1#', $compiledRoute->getRegex(), $m)) {
if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
$conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
$hasTrailingSlash = true;
@@ -205,6 +232,10 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren
$matches = true;
}
+ if ($compiledRoute->getHostnameVariables()) {
+ $hostnameMatches = true;
+ }
+
$conditions = implode(' && ', $conditions);
$code .= <<<EOF
@@ -263,14 +294,21 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren
}
// optimize parameters array
- if (true === $matches && $route->getDefaults()) {
- $code .= sprintf(" return array_merge(\$this->mergeDefaults(\$matches, %s), array('_route' => '%s'));\n"
- , str_replace("\n", '', var_export($route->getDefaults(), true)), $name);
- } elseif (true === $matches) {
- $code .= sprintf(" \$matches['_route'] = '%s';\n\n", $name);
- $code .= " return \$matches;\n";
+ if ($matches || $hostnameMatches) {
+ $vars = array();
+ if ($hostnameMatches) {
+ $vars[] = '$hostnameMatches';
+ }
+ if ($matches) {
+ $vars[] = '$matches';
+ }
+ $vars[] = "array('_route' => '$name')";
+
+ $code .= sprintf(" return \$this->mergeDefaults(array_replace(%s), %s);\n"
+ , implode(', ', $vars), str_replace("\n", '', var_export($route->getDefaults(), true)));
+
} elseif ($route->getDefaults()) {
- $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_merge($route->getDefaults(), array('_route' => $name)), true)));
+ $code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
} else {
$code .= sprintf(" return array('_route' => '%s');\n", $name);
}
@@ -284,10 +322,10 @@ private function compileRoute(Route $route, $name, $supportsRedirections, $paren
}
/**
- * Flattens a tree of routes to a single collection
+ * Flattens a tree of routes to a single collection.
*
- * @param RouteCollection $routes Collection of routes
- * @param DumperCollection $to A DumperCollection to add routes to
+ * @param RouteCollection $routes Collection of routes
+ * @param DumperCollection $to A DumperCollection to add routes to
*
* @return DumperCollection
*/
@@ -309,12 +347,42 @@ private function flattenRouteCollection(RouteCollection $routes, DumperCollectio
}
/**
+ * Groups consecutive routes having the same hostname regex.
+ *
+ * The results is a collection of collections of routes having the same hostname regex.
+ *
+ * @param DumperCollection $routes Flat collection of DumperRoutes
+ *
+ * @return DumperCollection A collection with routes grouped by hostname regex in sub-collections
+ */
+ private function groupRoutesByHostnameRegex(DumperCollection $routes)
+ {
+ $groups = new DumperCollection();
+
+ $currentGroup = new DumperCollection();
+ $currentGroup->setAttribute('hostname_regex', null);
+ $groups->add($currentGroup);
+
+ foreach ($routes as $route) {
+ $hostnameRegex = $route->getRoute()->compile()->getHostnameRegex();
+ if ($currentGroup->getAttribute('hostname_regex') !== $hostnameRegex) {
+ $currentGroup = new DumperCollection();
+ $currentGroup->setAttribute('hostname_regex', $hostnameRegex);
+ $groups->add($currentGroup);
+ }
+ $currentGroup->add($route);
+ }
+
+ return $groups;
+ }
+
+ /**
* Organizes the routes into a prefix tree.
*
* Routes order is preserved such that traversing the tree will traverse the
* routes in the origin order
*
- * @param DumperCollection $collection A collection of routes
+ * @param DumperCollection $collection A collection of routes
*
* @return DumperPrefixCollection
*/
@@ -331,5 +399,4 @@ private function buildPrefixTree(DumperCollection $collection)
return $tree;
}
-
}
View
7 src/Symfony/Component/Routing/Matcher/UrlMatcher.php
@@ -118,6 +118,11 @@ protected function matchCollection($pathinfo, RouteCollection $routes)
continue;
}
+ $hostnameMatches = array();
+ if ($compiledRoute->getHostnameRegex() && !preg_match($compiledRoute->getHostnameRegex(), $this->context->getHost(), $hostnameMatches)) {
+ continue;
+ }
+
// check HTTP method requirement
if ($req = $route->getRequirement('_method')) {
// HEAD and GET are equivalent as per RFC
@@ -142,7 +147,7 @@ protected function matchCollection($pathinfo, RouteCollection $routes)
continue;
}
- return array_merge($this->mergeDefaults($matches, $route->getDefaults()), array('_route' => $name));
+ return $this->mergeDefaults(array_replace($matches, $hostnameMatches, array('_route' => $name)), $route->getDefaults());
}
}
View
27 src/Symfony/Component/Routing/Route.php
@@ -25,6 +25,7 @@ class Route implements \Serializable
private $requirements;
private $options;
private $compiled;
+ private $hostnamePattern;
private static $compilers = array();
@@ -39,15 +40,17 @@ class Route implements \Serializable
* @param array $defaults An array of default parameter values
* @param array $requirements An array of requirements for parameters (regexes)
* @param array $options An array of options
+ * @param string $hostname The hostname pattern to match
*
* @api
*/
- public function __construct($pattern, array $defaults = array(), array $requirements = array(), array $options = array())
+ public function __construct($pattern, array $defaults = array(), array $requirements = array(), array $options = array(), $hostnamePattern = '')
{
$this->setPattern($pattern);
$this->setDefaults($defaults);
$this->setRequirements($requirements);
$this->setOptions($options);
+ $this->setHostnamePattern($hostnamePattern);
}
public function __clone()
@@ -104,6 +107,28 @@ public function setPattern($pattern)
}
/**
+ * Returns the hostname pattern.
+ *
+ * @return string The pattern
+ */
+ public function getHostnamePattern()
+ {
+ return $this->hostnamePattern;
+ }
+
+ /**
+ * Sets the hostname pattern.
+ *
+ * @param string $pattern The pattern
+ */
+ public function setHostnamePattern($pattern)
+ {
+ $this->hostnamePattern = (string) $pattern;
+
+ return $this;
+ }
+
+ /**
* Returns the options.
*
* @return array The options
View
44 src/Symfony/Component/Routing/RouteCollection.php
@@ -30,6 +30,7 @@ class RouteCollection implements \IteratorAggregate, \Countable
private $resources;
private $prefix;
private $parent;
+ private $hostnamePattern;
/**
* Constructor.
@@ -41,6 +42,7 @@ public function __construct()
$this->routes = array();
$this->resources = array();
$this->prefix = '';
+ $this->hostnamePattern = '';
}
public function __clone()
@@ -183,17 +185,18 @@ public function remove($name)
/**
* Adds a route collection to the current set of routes (at the end of the current set).
*
- * @param RouteCollection $collection A RouteCollection instance
- * @param string $prefix An optional prefix to add before each pattern of the route collection
- * @param array $defaults An array of default values
- * @param array $requirements An array of requirements
- * @param array $options An array of options
+ * @param RouteCollection $collection A RouteCollection instance
+ * @param string $prefix An optional prefix to add before each pattern of the route collection
+ * @param array $defaults An array of default values
+ * @param array $requirements An array of requirements
+ * @param array $options An array of options
+ * @param string $hostnamePattern Hostname pattern
*
* @throws \InvalidArgumentException When the RouteCollection already exists in the tree
*
* @api
*/
- public function addCollection(RouteCollection $collection, $prefix = '', $defaults = array(), $requirements = array(), $options = array())
+ public function addCollection(RouteCollection $collection, $prefix = '', $defaults = array(), $requirements = array(), $options = array(), $hostnamePattern = '')
{
// prevent infinite loops by recursive referencing
$root = $this->getRoot();
@@ -208,6 +211,11 @@ public function addCollection(RouteCollection $collection, $prefix = '', $defaul
// the sub-collection must have the prefix of the parent (current instance) prepended because it does not
// necessarily already have it applied (depending on the order RouteCollections are added to each other)
$collection->addPrefix($this->getPrefix() . $prefix, $defaults, $requirements, $options);
+
+ if ('' !== $hostnamePattern) {
+ $collection->setHostnamePattern($hostnamePattern);
+ }
+
$this->routes[] = $collection;
}
@@ -260,6 +268,30 @@ public function getPrefix()
}
/**
+ * Returns the hostname pattern.
+ *
+ * @return string The pattern
+ */
+ public function getHostnamePattern()
+ {
+ return $this->hostnamePattern;
+ }
+
+ /**
+ * Sets the hostname pattern on this collection and all children.
+ *
+ * @param string $pattern The pattern
+ */
+ public function setHostnamePattern($pattern)
+ {
+ $this->hostnamePattern = (string) $pattern;
+
+ foreach ($this->routes as $name => $route) {
+ $route->setHostnamePattern($pattern);
+ }
+ }
+
+ /**
* Returns an array of resources loaded to build this collection.
*
* @return ResourceInterface[] An array of resources
View
76 src/Symfony/Component/Routing/RouteCompiler.php
@@ -37,11 +37,57 @@ class RouteCompiler implements RouteCompilerInterface
*/
public function compile(Route $route)
{
+ $staticPrefix = null;
+ $hostnameVariables = array();
+ $pathVariables = array();
+ $variables = array();
+ $tokens = array();
+ $regex = null;
+ $hostnameRegex = null;
+ $hostnameTokens = array();
+
+ if ('' !== $hostnamePattern = $route->getHostnamePattern()) {
+ $result = $this->compilePattern($route, $hostnamePattern, true);
+
+ $hostnameVariables = $result['variables'];
+ $variables = array_merge($variables, $hostnameVariables);
+
+ $hostnameTokens = $result['tokens'];
+ $hostnameRegex = $result['regex'];
+ }
+
$pattern = $route->getPattern();
+
+ $result = $this->compilePattern($route, $pattern, false);
+
+ $staticPrefix = $result['staticPrefix'];
+
+ $pathVariables = $result['variables'];
+ $variables = array_merge($variables, $pathVariables);
+
+ $tokens = $result['tokens'];
+ $regex = $result['regex'];
+
+ return new CompiledRoute(
+ $staticPrefix,
+ $regex,
+ $tokens,
+ $pathVariables,
+ $hostnameRegex,
+ $hostnameTokens,
+ $hostnameVariables,
+ array_unique($variables)
+ );
+ }
+
+ private function compilePattern(Route $route, $pattern, $isHostname)
+ {
+ $len = strlen($pattern);
$tokens = array();
$variables = array();
$matches = array();
$pos = 0;
+ $defaultSeparator = $isHostname ? '.' : '/';
// Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
// in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
@@ -78,7 +124,11 @@ public function compile(Route $route)
// Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
// part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
$nextSeparator = $this->findNextSeparator($followingPattern);
- $regexp = sprintf('[^/%s]+', '/' !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : '');
+ $regexp = sprintf(
+ '[^%s%s]+',
+ preg_quote($defaultSeparator, self::REGEX_DELIMITER),
+ $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
+ );
if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) {
// When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
// quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
@@ -99,12 +149,14 @@ public function compile(Route $route)
// find the first optional token
$firstOptional = INF;
- for ($i = count($tokens) - 1; $i >= 0; $i--) {
- $token = $tokens[$i];
- if ('variable' === $token[0] && $route->hasDefault($token[3])) {
- $firstOptional = $i;
- } else {
- break;
+ if (!$isHostname) {
+ for ($i = count($tokens) - 1; $i >= 0; $i--) {
+ $token = $tokens[$i];
+ if ('variable' === $token[0] && $route->hasDefault($token[3])) {
+ $firstOptional = $i;
+ } else {
+ break;
+ }
}
}
@@ -114,11 +166,11 @@ public function compile(Route $route)
$regexp .= $this->computeRegexp($tokens, $i, $firstOptional);
}
- return new CompiledRoute(
- 'text' === $tokens[0][0] ? $tokens[0][1] : '',
- self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'s',
- array_reverse($tokens),
- $variables
+ return array(
+ 'staticPrefix' => 'text' === $tokens[0][0] ? $tokens[0][1] : '',
+ 'regex' => self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'s',
+ 'tokens' => array_reverse($tokens),
+ 'variables' => $variables,
);
}
View
3  src/Symfony/Component/Routing/Tests/Annotation/RouteTest.php
@@ -39,7 +39,8 @@ public function getValidParameters()
array('requirements', array('_method' => 'GET'), 'getRequirements'),
array('options', array('compiler_class' => 'RouteCompiler'), 'getOptions'),
array('name', 'blog_index', 'getName'),
- array('defaults', array('_controller' => 'MyBlogBundle:Blog:index'), 'getDefaults')
+ array('defaults', array('_controller' => 'MyBlogBundle:Blog:index'), 'getDefaults'),
+ array('hostname_pattern', array('{locale}.example.com'), 'getHostnamePattern')
);
}
}
View
10 src/Symfony/Component/Routing/Tests/CompiledRouteTest.php
@@ -17,10 +17,10 @@ class CompiledRouteTest extends \PHPUnit_Framework_TestCase
{
public function testAccessors()
{
- $compiled = new CompiledRoute('prefix', 'regex', array('tokens'), array('variables'));
- $this->assertEquals('prefix', $compiled->getStaticPrefix(), '__construct() takes a static prefix as its first argument');
- $this->assertEquals('regex', $compiled->getRegex(), '__construct() takes a regexp as its second argument');
- $this->assertEquals(array('tokens'), $compiled->getTokens(), '__construct() takes an array of tokens as its third argument');
- $this->assertEquals(array('variables'), $compiled->getVariables(), '__construct() takes an array of variables as its forth argument');
+ $compiled = new CompiledRoute('prefix', 'regex', array('tokens'), array(), array(), array(), array(), array('variables'));
+ $this->assertEquals('prefix', $compiled->getStaticPrefix(), '__construct() takes a static prefix as its second argument');
+ $this->assertEquals('regex', $compiled->getRegex(), '__construct() takes a regexp as its third argument');
+ $this->assertEquals(array('tokens'), $compiled->getTokens(), '__construct() takes an array of tokens as its fourth argument');
+ $this->assertEquals(array('variables'), $compiled->getVariables(), '__construct() takes an array of variables as its ninth argument');
}
}
View
94 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.apache
@@ -68,8 +68,96 @@ RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz6,E=_ROUTING_default_foo:bar\
RewriteCond %{REQUEST_URI} ^/te\ st/baz$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz7]
+# baz8
+RewriteCond %{REQUEST_URI} ^/te\\\ st/baz$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz8]
+
+# baz9
+RewriteCond %{REQUEST_URI} ^/test/(te\\\ st)$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz9,E=_ROUTING_param_baz:%1]
+
+RewriteCond %{HTTP:Host} ^a\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_1:1]
+
+# route1
+RewriteCond %{ENV:__ROUTING_hostname_1} =1
+RewriteCond %{REQUEST_URI} ^/route1$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route1]
+
+# route2
+RewriteCond %{ENV:__ROUTING_hostname_1} =1
+RewriteCond %{REQUEST_URI} ^/c2/route2$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route2]
+
+RewriteCond %{HTTP:Host} ^b\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_2:1]
+
+# route3
+RewriteCond %{ENV:__ROUTING_hostname_2} =1
+RewriteCond %{REQUEST_URI} ^/c2/route3$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route3]
+
+RewriteCond %{HTTP:Host} ^a\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_3:1]
+
+# route4
+RewriteCond %{ENV:__ROUTING_hostname_3} =1
+RewriteCond %{REQUEST_URI} ^/route4$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route4]
+
+RewriteCond %{HTTP:Host} ^c\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_4:1]
+
+# route5
+RewriteCond %{ENV:__ROUTING_hostname_4} =1
+RewriteCond %{REQUEST_URI} ^/route5$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route5]
+
+# route6
+RewriteCond %{REQUEST_URI} ^/route6$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route6]
+
+RewriteCond %{HTTP:Host} ^([^\.]++)\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_5:1,E=__ROUTING_hostname_5_var1:%1]
+
+# route11
+RewriteCond %{ENV:__ROUTING_hostname_5} =1
+RewriteCond %{REQUEST_URI} ^/route11$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route11,E=_ROUTING_param_var1:%{ENV:__ROUTING_hostname_5_var1}]
+
+# route12
+RewriteCond %{ENV:__ROUTING_hostname_5} =1
+RewriteCond %{REQUEST_URI} ^/route12$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route12,E=_ROUTING_param_var1:%{ENV:__ROUTING_hostname_5_var1},E=_ROUTING_default_var1:val]
+
+# route13
+RewriteCond %{ENV:__ROUTING_hostname_5} =1
+RewriteCond %{REQUEST_URI} ^/route13/([^/]++)$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route13,E=_ROUTING_param_var1:%{ENV:__ROUTING_hostname_5_var1},E=_ROUTING_param_name:%1]
+
+# route14
+RewriteCond %{ENV:__ROUTING_hostname_5} =1
+RewriteCond %{REQUEST_URI} ^/route14/([^/]++)$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route14,E=_ROUTING_param_var1:%{ENV:__ROUTING_hostname_5_var1},E=_ROUTING_param_name:%1,E=_ROUTING_default_var1:val]
+
+RewriteCond %{HTTP:Host} ^c\.example\.com$
+RewriteRule .? - [E=__ROUTING_hostname_6:1]
+
+# route15
+RewriteCond %{ENV:__ROUTING_hostname_6} =1
+RewriteCond %{REQUEST_URI} ^/route15/([^/]++)$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route15,E=_ROUTING_param_name:%1]
+
+# route16
+RewriteCond %{REQUEST_URI} ^/route16/([^/]++)$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route16,E=_ROUTING_param_name:%1,E=_ROUTING_default_var1:val]
+
+# route17
+RewriteCond %{REQUEST_URI} ^/route17$
+RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route17]
+
# 405 Method Not Allowed
-RewriteCond %{_ROUTING_allow_GET} !-z [OR]
-RewriteCond %{_ROUTING_allow_HEAD} !-z [OR]
-RewriteCond %{_ROUTING_allow_POST} !-z
+RewriteCond %{ENV:_ROUTING__allow_GET} =1 [OR]
+RewriteCond %{ENV:_ROUTING__allow_HEAD} =1 [OR]
+RewriteCond %{ENV:_ROUTING__allow_POST} =1
RewriteRule .* app.php [QSA,L]
View
169 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.php
@@ -27,7 +27,7 @@ public function match($pathinfo)
// foo
if (0 === strpos($pathinfo, '/foo') && preg_match('#^/foo/(?<bar>baz|symfony)$#s', $pathinfo, $matches)) {
- return array_merge($this->mergeDefaults($matches, array ( 'def' => 'test',)), array('_route' => 'foo'));
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo')), array ( 'def' => 'test',));
}
if (0 === strpos($pathinfo, '/bar')) {
@@ -38,9 +38,7 @@ public function match($pathinfo)
goto not_bar;
}
- $matches['_route'] = 'bar';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar')), array ());
}
not_bar:
@@ -51,9 +49,7 @@ public function match($pathinfo)
goto not_barhead;
}
- $matches['_route'] = 'barhead';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'barhead')), array ());
}
not_barhead:
@@ -80,9 +76,7 @@ public function match($pathinfo)
// baz4
if (preg_match('#^/test/(?<foo>[^/]++)/$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'baz4';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz4')), array ());
}
// baz5
@@ -92,9 +86,7 @@ public function match($pathinfo)
goto not_baz5;
}
- $matches['_route'] = 'baz5';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz5')), array ());
}
not_baz5:
@@ -105,9 +97,7 @@ public function match($pathinfo)
goto not_bazbaz6;
}
- $matches['_route'] = 'baz.baz6';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz.baz6')), array ());
}
not_bazbaz6:
@@ -120,9 +110,7 @@ public function match($pathinfo)
// quoter
if (preg_match('#^/(?<quoter>[\']+)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'quoter';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'quoter')), array ());
}
// space
@@ -134,40 +122,30 @@ public function match($pathinfo)
if (0 === strpos($pathinfo, '/a/b\'b')) {
// foo1
if (preg_match('#^/a/b\'b/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo1';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo1')), array ());
}
// bar1
if (preg_match('#^/a/b\'b/(?<bar>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar1';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar1')), array ());
}
}
// overridden
if (preg_match('#^/a/(?<var>.*)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'overridden';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'overridden')), array ());
}
if (0 === strpos($pathinfo, '/a/b\'b')) {
// foo2
if (preg_match('#^/a/b\'b/(?<foo1>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo2';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo2')), array ());
}
// bar2
if (preg_match('#^/a/b\'b/(?<bar1>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar2';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar2')), array ());
}
}
@@ -177,7 +155,7 @@ public function match($pathinfo)
if (0 === strpos($pathinfo, '/multi')) {
// helloWorld
if (0 === strpos($pathinfo, '/multi/hello') && preg_match('#^/multi/hello(?:/(?<who>[^/]++))?$#s', $pathinfo, $matches)) {
- return array_merge($this->mergeDefaults($matches, array ( 'who' => 'World!',)), array('_route' => 'helloWorld'));
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'helloWorld')), array ( 'who' => 'World!',));
}
// overridden2
@@ -194,34 +172,119 @@ public function match($pathinfo)
// foo3
if (preg_match('#^/(?<_locale>[^/]++)/b/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo3';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo3')), array ());
}
// bar3
if (preg_match('#^/(?<_locale>[^/]++)/b/(?<bar>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar3';
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar3')), array ());
+ }
+
+ if (0 === strpos($pathinfo, '/aba')) {
+ // ababa
+ if ($pathinfo === '/ababa') {
+ return array('_route' => 'ababa');
+ }
+
+ // foo4
+ if (preg_match('#^/aba/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo4')), array ());
+ }
- return $matches;
}
- if (0 === strpos($pathinfo, '/a')) {
- if (0 === strpos($pathinfo, '/aba')) {
- // ababa
- if ($pathinfo === '/ababa') {
- return array('_route' => 'ababa');
+ $hostname = $this->context->getHost();
+
+ if (preg_match('#^a\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route1
+ if ($pathinfo === '/route1') {
+ return array('_route' => 'route1');
+ }
+
+ // route2
+ if ($pathinfo === '/c2/route2') {
+ return array('_route' => 'route2');
+ }
+
+ }
+
+ if (preg_match('#^b\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route3
+ if ($pathinfo === '/c2/route3') {
+ return array('_route' => 'route3');
+ }
+
+ }
+
+ if (preg_match('#^a\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route4
+ if ($pathinfo === '/route4') {
+ return array('_route' => 'route4');
+ }
+
+ }
+
+ if (preg_match('#^c\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route5
+ if ($pathinfo === '/route5') {
+ return array('_route' => 'route5');
+ }
+
+ }
+
+ // route6
+ if ($pathinfo === '/route6') {
+ return array('_route' => 'route6');
+ }
+
+ if (preg_match('#^(?<var1>[^\\.]++)\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ if (0 === strpos($pathinfo, '/route1')) {
+ // route11
+ if ($pathinfo === '/route11') {
+ return $this->mergeDefaults(array_replace($hostnameMatches, array('_route' => 'route11')), array ());
}
- // foo4
- if (preg_match('#^/aba/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo4';
+ // route12
+ if ($pathinfo === '/route12') {
+ return $this->mergeDefaults(array_replace($hostnameMatches, array('_route' => 'route12')), array ( 'var1' => 'val',));
+ }
- return $matches;
+ // route13
+ if (0 === strpos($pathinfo, '/route13') && preg_match('#^/route13/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($hostnameMatches, $matches, array('_route' => 'route13')), array ());
}
+ // route14
+ if (0 === strpos($pathinfo, '/route14') && preg_match('#^/route14/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($hostnameMatches, $matches, array('_route' => 'route14')), array ( 'var1' => 'val',));
+ }
+
+ }
+
+ }
+
+ if (preg_match('#^c\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route15
+ if (0 === strpos($pathinfo, '/route15') && preg_match('#^/route15/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'route15')), array ());
+ }
+
+ }
+
+ if (0 === strpos($pathinfo, '/route1')) {
+ // route16
+ if (0 === strpos($pathinfo, '/route16') && preg_match('#^/route16/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'route16')), array ( 'var1' => 'val',));
}
+ // route17
+ if ($pathinfo === '/route17') {
+ return array('_route' => 'route17');
+ }
+
+ }
+
+ if (0 === strpos($pathinfo, '/a')) {
// a
if ($pathinfo === '/a/a...') {
return array('_route' => 'a');
@@ -230,16 +293,12 @@ public function match($pathinfo)
if (0 === strpos($pathinfo, '/a/b')) {
// b
if (preg_match('#^/a/b/(?<var>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'b';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'b')), array ());
}
// c
if (0 === strpos($pathinfo, '/a/b/c') && preg_match('#^/a/b/c/(?<var>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'c';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'c')), array ());
}
}
View
169 src/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.php
@@ -27,7 +27,7 @@ public function match($pathinfo)
// foo
if (0 === strpos($pathinfo, '/foo') && preg_match('#^/foo/(?<bar>baz|symfony)$#s', $pathinfo, $matches)) {
- return array_merge($this->mergeDefaults($matches, array ( 'def' => 'test',)), array('_route' => 'foo'));
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo')), array ( 'def' => 'test',));
}
if (0 === strpos($pathinfo, '/bar')) {
@@ -38,9 +38,7 @@ public function match($pathinfo)
goto not_bar;
}
- $matches['_route'] = 'bar';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar')), array ());
}
not_bar:
@@ -51,9 +49,7 @@ public function match($pathinfo)
goto not_barhead;
}
- $matches['_route'] = 'barhead';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'barhead')), array ());
}
not_barhead:
@@ -88,9 +84,7 @@ public function match($pathinfo)
return $this->redirect($pathinfo.'/', 'baz4');
}
- $matches['_route'] = 'baz4';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz4')), array ());
}
// baz5
@@ -100,9 +94,7 @@ public function match($pathinfo)
goto not_baz5;
}
- $matches['_route'] = 'baz5';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz5')), array ());
}
not_baz5:
@@ -113,9 +105,7 @@ public function match($pathinfo)
goto not_bazbaz6;
}
- $matches['_route'] = 'baz.baz6';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz.baz6')), array ());
}
not_bazbaz6:
@@ -128,9 +118,7 @@ public function match($pathinfo)
// quoter
if (preg_match('#^/(?<quoter>[\']+)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'quoter';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'quoter')), array ());
}
// space
@@ -142,40 +130,30 @@ public function match($pathinfo)
if (0 === strpos($pathinfo, '/a/b\'b')) {
// foo1
if (preg_match('#^/a/b\'b/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo1';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo1')), array ());
}
// bar1
if (preg_match('#^/a/b\'b/(?<bar>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar1';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar1')), array ());
}
}
// overridden
if (preg_match('#^/a/(?<var>.*)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'overridden';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'overridden')), array ());
}
if (0 === strpos($pathinfo, '/a/b\'b')) {
// foo2
if (preg_match('#^/a/b\'b/(?<foo1>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo2';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo2')), array ());
}
// bar2
if (preg_match('#^/a/b\'b/(?<bar1>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar2';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar2')), array ());
}
}
@@ -185,7 +163,7 @@ public function match($pathinfo)
if (0 === strpos($pathinfo, '/multi')) {
// helloWorld
if (0 === strpos($pathinfo, '/multi/hello') && preg_match('#^/multi/hello(?:/(?<who>[^/]++))?$#s', $pathinfo, $matches)) {
- return array_merge($this->mergeDefaults($matches, array ( 'who' => 'World!',)), array('_route' => 'helloWorld'));
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'helloWorld')), array ( 'who' => 'World!',));
}
// overridden2
@@ -206,34 +184,119 @@ public function match($pathinfo)
// foo3
if (preg_match('#^/(?<_locale>[^/]++)/b/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo3';
-
- return $matches;
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo3')), array ());
}
// bar3
if (preg_match('#^/(?<_locale>[^/]++)/b/(?<bar>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'bar3';
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar3')), array ());
+ }
+
+ if (0 === strpos($pathinfo, '/aba')) {
+ // ababa
+ if ($pathinfo === '/ababa') {
+ return array('_route' => 'ababa');
+ }
+
+ // foo4
+ if (preg_match('#^/aba/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo4')), array ());
+ }
- return $matches;
}
- if (0 === strpos($pathinfo, '/a')) {
- if (0 === strpos($pathinfo, '/aba')) {
- // ababa
- if ($pathinfo === '/ababa') {
- return array('_route' => 'ababa');
+ $hostname = $this->context->getHost();
+
+ if (preg_match('#^a\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route1
+ if ($pathinfo === '/route1') {
+ return array('_route' => 'route1');
+ }
+
+ // route2
+ if ($pathinfo === '/c2/route2') {
+ return array('_route' => 'route2');
+ }
+
+ }
+
+ if (preg_match('#^b\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route3
+ if ($pathinfo === '/c2/route3') {
+ return array('_route' => 'route3');
+ }
+
+ }
+
+ if (preg_match('#^a\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route4
+ if ($pathinfo === '/route4') {
+ return array('_route' => 'route4');
+ }
+
+ }
+
+ if (preg_match('#^c\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route5
+ if ($pathinfo === '/route5') {
+ return array('_route' => 'route5');
+ }
+
+ }
+
+ // route6
+ if ($pathinfo === '/route6') {
+ return array('_route' => 'route6');
+ }
+
+ if (preg_match('#^(?<var1>[^\\.]++)\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ if (0 === strpos($pathinfo, '/route1')) {
+ // route11
+ if ($pathinfo === '/route11') {
+ return $this->mergeDefaults(array_replace($hostnameMatches, array('_route' => 'route11')), array ());
}
- // foo4
- if (preg_match('#^/aba/(?<foo>[^/]++)$#s', $pathinfo, $matches)) {
- $matches['_route'] = 'foo4';
+ // route12
+ if ($pathinfo === '/route12') {
+ return $this->mergeDefaults(array_replace($hostnameMatches, array('_route' => 'route12')), array ( 'var1' => 'val',));
+ }
- return $matches;
+ // route13
+ if (0 === strpos($pathinfo, '/route13') && preg_match('#^/route13/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($hostnameMatches, $matches, array('_route' => 'route13')), array ());
}
+ // route14
+ if (0 === strpos($pathinfo, '/route14') && preg_match('#^/route14/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($hostnameMatches, $matches, array('_route' => 'route14')), array ( 'var1' => 'val',));
+ }
+
+ }
+
+ }
+
+ if (preg_match('#^c\\.example\\.com$#s', $hostname, $hostnameMatches)) {
+ // route15
+ if (0 === strpos($pathinfo, '/route15') && preg_match('#^/route15/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'route15')), array ());
+ }
+
+ }
+
+ if (0 === strpos($pathinfo, '/route1')) {
+ // route16
+ if (0 === strpos($pathinfo, '/route16') && preg_match('#^/route16/(?<name>[^/]++)$#s', $pathinfo, $matches)) {
+ return $this->mergeDefaults(array_replace($matches, array('_route' => 'route16')), array ( 'var1' => 'val',));
}
+ // route17
+ if ($pathinfo === '/route17') {
+ return array('_route' => 'route17');
+ }
+
+ }
+
+ if (0 === strpos($pathinfo, '/a')) {
// a
if ($pathinfo === '/a/a...') {