Преглед изворни кода

merged branch ericclemmons/fix-router-generator-empty-query-string (PR #1773)

Commits
-------

03c7cfe UrlGenerator no longer appends '?' if query string is empty

Discussion
----------

UrlGenerator no longer appends '?' if query string is empty

If you generate a URL using null parameters (`array('foo' => null, 'bar' => null')`), `http_build_query` returns an empty string, resulting in a trailing `?` at the end of the generated URL.

This fixes that so that, if there are `$extra` params & `http_build_query` is empty, the URL is no longer appended.

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

by fabpot at 2011/07/22 10:15:26 -0700

Can you add unit tests?

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

by ericclemmons at 2011/07/22 10:52:21 -0700

Yes sir, will do.

-Eric Clemmons
 Sent from my iPad Nano

On Jul 22, 2011, at 12:15 PM, fabpot<reply@reply.github.com> wrote:

> Can you add unit tests?
>
> --
> Reply to this email directly or view it on GitHub:
> https://github.com/symfony/symfony/pull/1773#issuecomment-1633515

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

by ericclemmons at 2011/07/22 11:55:30 -0700

**Added passing test.**

Currently `master` fails test:

```
1) Symfony\Tests\Component\Routing\Generator\UrlGeneratorTest::testUrlWithNullExtraParameters
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-http://localhost/app.php/testing
+http://localhost/app.php/testing?

//tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php:114
```
Fabien Potencier пре 14 година
родитељ
комит
18894762ee

+ 3 - 2
src/Symfony/Component/Routing/Generator/UrlGenerator.php

@@ -145,8 +145,9 @@ class UrlGenerator implements UrlGeneratorInterface
         }
 
         // add a query string if needed
-        if ($extra = array_diff_key($originParameters, $variables, $defaults)) {
-            $url .= '?'.http_build_query($extra);
+        $extra = array_diff_key($originParameters, $variables, $defaults);
+        if ($extra && $query = http_build_query($extra)) {
+            $url .= '?'.$query;
         }
 
         $url = $this->context->getBaseUrl().$url;

+ 8 - 0
tests/Symfony/Tests/Component/Routing/Generator/UrlGeneratorTest.php

@@ -106,6 +106,14 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals('http://localhost/app.php/testing?foo=bar', $url);
     }
 
+    public function testUrlWithNullExtraParameters()
+    {
+        $routes = $this->getRoutes('test', new Route('/testing'));
+        $url = $this->getGenerator($routes)->generate('test', array('foo' => null), true);
+
+        $this->assertEquals('http://localhost/app.php/testing', $url);
+    }
+
     public function testUrlWithExtraParametersFromGlobals()
     {
         $routes = $this->getRoutes('test', new Route('/testing'));