[Routing] add query param if value is different from default

This commit is contained in:
Tobias Schultze 2016-03-23 18:41:29 +01:00
parent a5965fb23b
commit 1ef2edf4b4
2 changed files with 19 additions and 4 deletions

View File

@ -257,7 +257,10 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt
}
// add a query string if needed
$extra = array_diff_key($parameters, $variables, $defaults);
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
$url .= '?'.$query;
}

View File

@ -291,10 +291,22 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
public function testQueryParamSameAsDefault()
{
$routes = $this->getRoutes('test', new Route('/test', array('default' => 'value')));
$routes = $this->getRoutes('test', new Route('/test', array('page' => 1)));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('default' => 'foo')));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('default' => 'value')));
$this->assertSame('/app.php/test?page=2', $this->getGenerator($routes)->generate('test', array('page' => 2)));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('page' => 1)));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('page' => '1')));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test'));
}
public function testArrayQueryParamSameAsDefault()
{
$routes = $this->getRoutes('test', new Route('/test', array('array' => array('foo', 'bar'))));
$this->assertSame('/app.php/test?array%5B0%5D=bar&array%5B1%5D=foo', $this->getGenerator($routes)->generate('test', array('array' => array('bar', 'foo'))));
$this->assertSame('/app.php/test?array%5Ba%5D=foo&array%5Bb%5D=bar', $this->getGenerator($routes)->generate('test', array('array' => array('a' => 'foo', 'b' => 'bar'))));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('array' => array('foo', 'bar'))));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('array' => array(1 => 'bar', 0 => 'foo'))));
$this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test'));
}