Skip to content

[Routing] Allow query-specific parameters in UrlGenerator using _query #60508

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Routing/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Allow aliases and deprecations in `#[Route]` attribute
* Add the `Requirement::MONGODB_ID` constant to validate MongoDB ObjectIDs in hexadecimal format
* Allow query-specific parameters in `UrlGenerator` using `_query`

7.2
---
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Routing/Generator/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,17 @@ public function generate(string $name, array $parameters = [], int $referenceTyp
*/
protected function doGenerate(array $variables, array $defaults, array $requirements, array $tokens, array $parameters, string $name, int $referenceType, array $hostTokens, array $requiredSchemes = []): string
{
if (isset($parameters['_query'])) {
if (!is_array($parameters['_query'])) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About the potential BC break: Right now one could use a parameter named _query perfectly fine. But... if I don't miss anything it must be a scalar value, right? If I am not mistaken, what about only treating _query with its special meaning for URL parameters when it is an array (at least for a transition period where we could trigger a deprecation)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is nice, but I'm afraid arrays are accepted just fine right now. We could still lower the scope of the potential BC break by letting '_query' => scalar go through, although I'm not sure if this would make the whole thing even more confusing.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's happening right now without your changes when an array is passed?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a an array in the query parameter then, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it behaves just like http_build_query() does with arrays: ?foo[x]=y (spared you the percent encoding).

throw new InvalidParameterException('The "_query" parameter must be an array.');
}

$queryParameters = $parameters['_query'];
unset($parameters['_query']);
} else {
$queryParameters = [];
}

$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);

Expand Down Expand Up @@ -260,6 +271,7 @@ protected function doGenerate(array $variables, array $defaults, array $requirem

// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, fn ($a, $b) => $a == $b ? 0 : 1);
$extra = array_merge($extra, $queryParameters);

array_walk_recursive($extra, $caster = static function (&$v) use (&$caster) {
if (\is_object($v)) {
Expand Down
67 changes: 67 additions & 0 deletions src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,73 @@ public function testUtf8VarName()
$this->assertSame('/app.php/foo/baz', $this->getGenerator($routes)->generate('test', ['bär' => 'baz']));
}

public function testQueryParameters()
{
$routes = $this->getRoutes('user', new Route('/user/{username}'));
$url = $this->getGenerator($routes)->generate('user', [
'username' => 'john',
'a' => 'foo',
'b' => 'bar',
'c' => 'baz',
'_query' => [
'a' => '123',
'd' => '789',
],
]);
$this->assertSame('/app.php/user/john?a=123&b=bar&c=baz&d=789', $url);
}

public function testRouteHostParameterAndQueryParameterWithSameName()
{
$routes = $this->getRoutes('admin_stats', new Route('/admin/stats', requirements: ['domain' => '.+'], host: '{siteCode}.{domain}'));
$url = $this->getGenerator($routes)->generate('admin_stats', [
'siteCode' => 'fr',
'domain' => 'example.com',
'_query' => [
'siteCode' => 'us',
],
], UrlGeneratorInterface::NETWORK_PATH);
$this->assertSame('//fr.example.com/app.php/admin/stats?siteCode=us', $url);
}

public function testRoutePathParameterAndQueryParameterWithSameName()
{
$routes = $this->getRoutes('user', new Route('/user/{id}'));
$url = $this->getGenerator($routes)->generate('user', [
'id' => '123',
'_query' => [
'id' => '456',
],
]);
$this->assertSame('/app.php/user/123?id=456', $url);
}

public function testQueryParameterCannotSubstituteRouteParameter()
{
$routes = $this->getRoutes('user', new Route('/user/{id}'));

$this->expectException(MissingMandatoryParametersException::class);
$this->expectExceptionMessage('Some mandatory parameters are missing ("id") to generate a URL for route "user".');

$this->getGenerator($routes)->generate('user', [
'_query' => [
'id' => '456',
],
]);
}

public function testQueryParametersMustBeAnArray()
{
$routes = $this->getRoutes('user', new Route('/user/{id}'));

$this->expectException(InvalidParameterException::class);
$this->expectExceptionMessage('The "_query" parameter must be an array.');

$this->getGenerator($routes)->generate('user', [
'_query' => 'a=b',
]);
}

protected function getGenerator(RouteCollection $routes, array $parameters = [], $logger = null, ?string $defaultLocale = null)
{
$context = new RequestContext('/app.php');
Expand Down