Bug: method withQueryParameter cleans all previous parameters
osbre opened this issue · 3 comments
osbre commented
PHP: 7.4.13
Imagine this example:
$a = Url::fromString("https://spatie.be");
$a->withQueryParameter('you', 1);
$a->withQueryParameter('are', 2);
$a->withQueryParameter('awesome', 3);
echo $a->__toString();// https://spatie.be
Expected result:
https://spatie.be?you=1&are=2&awesome=3
Actual result:
https://spatie.be
How to fix
Remove __clone
method.
The problem is in the _clone
method, which probably had the purpose to fix this problem but now causes it. https://github.com/spatie/url/blob/master/src/Url.php#L345
freekmurze commented
We'll continue this in #42
sebastiandedeyne commented
This is not a bug, but the design of the package. As stated in the readme:
The
Url
class is immutable
The package is built like this because it follows PSR-7's UriInterface
, which must be immutable.
If you want to modify a URL, you need to reassign it.
$a = Url::fromString("https://spatie.be");
$b = $a
->withQueryParameter('you', 1)
->withQueryParameter('are', 2)
->withQueryParameter('awesome', 3);
echo $a->__toString(); // https://spatie.be
echo $b->__toString(); // https://spatie.be?you=1&are=2&awesome=3
osbre commented
Thanks for the explanation @sebastiandedeyne!