Skip to content

Commit 6cc0244

Browse files
committed
feat: Query::merge() + Params::merge()
1 parent 12186c3 commit 6cc0244

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed

src/Http/Params.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,23 @@ public function isNotEmpty(): bool
101101
return $this->isEmpty() === false;
102102
}
103103

104+
/**
105+
* Merges the current params with the given params
106+
* @since 5.1.0
107+
*
108+
* @return $this
109+
*/
110+
public function merge(array|string|null $params): static
111+
{
112+
$params = new static($params);
113+
114+
foreach ($params as $key => $value) {
115+
$this->$key = $value;
116+
}
117+
118+
return $this;
119+
}
120+
104121
/**
105122
* Returns the param separator according
106123
* to the operating system.

src/Http/Query.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,23 @@ public function isNotEmpty(): bool
3737
return $this->isEmpty() === false;
3838
}
3939

40+
/**
41+
* Merges the current query with the given query
42+
* @since 5.1.0
43+
*
44+
* @return $this
45+
*/
46+
public function merge(string|array|null $query): static
47+
{
48+
$query = new static($query);
49+
50+
foreach ($query as $key => $value) {
51+
$this->$key = $value;
52+
}
53+
54+
return $this;
55+
}
56+
4057
public function toString(bool $questionMark = false): string
4158
{
4259
$query = http_build_query($this, '', '&', PHP_QUERY_RFC3986);

tests/Http/ParamsTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,15 @@ public function testIsNotEmpty(): void
108108
$this->assertFalse($params->isNotEmpty());
109109
}
110110

111+
public function testMerge(): void
112+
{
113+
$params = new Params(['foo' => 'bar', 'bar' => 'baz']);
114+
$params->merge(['bar' => 'foo', 'baz' => 'qux']);
115+
$this->assertSame('bar', $params->foo);
116+
$this->assertSame('foo', $params->bar);
117+
$this->assertSame('qux', $params->baz);
118+
}
119+
111120
public function testToString(): void
112121
{
113122
$params = new Params([

tests/Http/QueryTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ public function testIsNotEmpty(): void
5353
$this->assertFalse($query->isNotEmpty());
5454
}
5555

56+
public function testMerge(): void
57+
{
58+
$params = new Query(['foo' => 'bar', 'bar' => 'baz']);
59+
$params->merge(['bar' => 'foo', 'baz' => 'qux']);
60+
$this->assertSame('bar', $params->foo);
61+
$this->assertSame('foo', $params->bar);
62+
$this->assertSame('qux', $params->baz);
63+
}
64+
5665
public function testToString(): void
5766
{
5867
$query = new Query([

0 commit comments

Comments
 (0)