Use the default host even if context is empty and fallback to relative URL if empty host

This commit is contained in:
Samuel ROZE 2017-12-14 09:15:05 +00:00
parent 8e54591f24
commit 8f357df75b
No known key found for this signature in database
GPG Key ID: 835426F55A19FB84
2 changed files with 74 additions and 43 deletions

View File

@ -181,7 +181,7 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$host = $this->context->getHost();
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
@ -227,7 +227,7 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
if ((self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) && !empty($host)) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
@ -238,7 +238,6 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);

View File

@ -469,6 +469,38 @@ class UrlGeneratorTest extends TestCase
$this->assertSame('//EN.FooBar.com/app.php/', $generator->generate('test', array('locale' => 'EN'), UrlGeneratorInterface::NETWORK_PATH));
}
public function testDefaultHostIsUsedWhenContextHostIsEmpty()
{
$routes = $this->getRoutes('test', new Route('/route', array('domain' => 'my.fallback.host'), array('domain' => '.+'), array(), '{domain}', array('http')));
$generator = $this->getGenerator($routes);
$generator->getContext()->setHost('');
$this->assertSame('http://my.fallback.host/app.php/route', $generator->generate('test', array(), UrlGeneratorInterface::ABSOLUTE_URL));
}
public function testDefaultHostIsUsedWhenContextHostIsEmptyAndSchemeIsNot()
{
$routes = $this->getRoutes('test', new Route('/route', array('domain' => 'my.fallback.host'), array('domain' => '.+'), array(), '{domain}', array('http', 'https')));
$generator = $this->getGenerator($routes);
$generator->getContext()->setHost('');
$generator->getContext()->setScheme('https');
$this->assertSame('https://my.fallback.host/app.php/route', $generator->generate('test', array(), UrlGeneratorInterface::ABSOLUTE_URL));
}
public function testAbsoluteUrlFallbackToRelativeIfHostIsEmptyAndSchemeIsNot()
{
$routes = $this->getRoutes('test', new Route('/route', array(), array(), array(), '', array('http', 'https')));
$generator = $this->getGenerator($routes);
$generator->getContext()->setHost('');
$generator->getContext()->setScheme('https');
$this->assertSame('/app.php/route', $generator->generate('test', array(), UrlGeneratorInterface::ABSOLUTE_URL));
}
/**
* @group legacy
*/