Skip to content

Commit

Permalink
Merge pull request #51 from rapkis/feature/set-multiple-query-parameters
Browse files Browse the repository at this point in the history
Add ability to set multiple query parameters at once
  • Loading branch information
freekmurze authored Feb 3, 2022
2 parents 8e274b7 + 5e4c9bd commit e3c53b4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ $url = Url::fromString('https://spatie.be/opensource?utm_source=github&utm_campa
echo $url->getQuery(); // 'utm_source=github&utm_campaign=packages'
echo $url->getQueryParameter('utm_source'); // 'github'
echo $url->withoutQueryParameter('utm_campaign'); // 'https://spatie.be/opensource?utm_source=github'
echo $url->withQueryParameters(['utm_campaign' => 'packages']); // 'https://spatie.be/opensource?utm_source=github&utm_campaign=packages'
```

Retrieve path segments:
Expand Down
9 changes: 9 additions & 0 deletions src/Url.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,15 @@ public function withQueryParameter(string $key, string $value): static
return $url;
}

public function withQueryParameters(array $parameters): static
{
$parameters = array_merge($this->getAllQueryParameters(), $parameters);
$url = clone $this;
$url->query = new QueryParameterBag($parameters);

return $url;
}

public function withoutQueryParameter(string $key): static
{
$url = clone $this;
Expand Down
18 changes: 18 additions & 0 deletions tests/UrlQueryParametersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@ public function it_can_set_a_query_parameter()
$this->assertSame('10', $url->getQueryParameter('offset'));
}

/** @test */
public function it_can_set_multiple_query_parameters()
{
$url = Url::create()->withQueryParameters(['offset' => 10, 'limit' => 5]);

$this->assertEquals('10', $url->getQueryParameter('offset'));
$this->assertEquals('5', $url->getQueryParameter('limit'));
}

/** @test */
public function it_merges_multiple_query_parameters()
{
$url = Url::create()->withQuery('offset=10')->withQueryParameters(['limit' => 5]);

$this->assertTrue($url->hasQueryParameter('offset'));
$this->assertTrue($url->hasQueryParameter('limit'));
}

/** @test */
public function it_can_check_if_it_has_a_query_parameter()
{
Expand Down

0 comments on commit e3c53b4

Please sign in to comment.