Skip to content

Commit 3eb61fe

Browse files
Merge pull request #7611 from getkirby/feat/uri-inherit
feat: `Uri::inherit()`
1 parent ea7a4b1 commit 3eb61fe

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/Http/Uri.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,27 @@ public static function index(array $props = []): static
303303
return new static($url, $props);
304304
}
305305

306+
/**
307+
* Inherit query, params and fragment from a parent Uri
308+
* @since 5.2.0
309+
* @return $this
310+
*/
311+
public function inherit(Uri|string $parent): static
312+
{
313+
if (is_string($parent) === true) {
314+
$parent = new static($parent);
315+
}
316+
317+
$this->query->merge($parent->query());
318+
$this->params->merge($parent->params());
319+
320+
if ($fragment = $parent->fragment()) {
321+
$this->setFragment($fragment);
322+
}
323+
324+
return $this;
325+
}
326+
306327
/**
307328
* Checks if the host exists
308329
*/

tests/Http/UriTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,21 @@ public function testIndexInCli(): void
164164
$this->assertSame('/', $uri->toString());
165165
}
166166

167+
public function testInherit(): void
168+
{
169+
$base = new Uri('https://getkirby.com');
170+
171+
$uri = $base->inherit('https://foo.com/this/is/a/path');
172+
$this->assertSame('https://getkirby.com', $uri->toString());
173+
174+
$uri = $base->inherit('https://foo.com/fox:bax?foo=bar#anchor');
175+
$this->assertSame('https://getkirby.com/fox:bax?foo=bar#anchor', $uri->toString());
176+
177+
$base = new Uri('https://getkirby.com?one=two');
178+
$uri = $base->inherit('https://foo.com/?foo=bar');
179+
$this->assertSame('https://getkirby.com?one=two&foo=bar', $uri->toString());
180+
}
181+
167182
public function testInvalidScheme(): void
168183
{
169184
$this->expectException(InvalidArgumentException::class);

0 commit comments

Comments
 (0)