Skip to content

Commit 1262195

Browse files
committed
Add URL::getRelative method
1 parent d17e9c7 commit 1262195

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

src/URL.php

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -284,16 +284,29 @@ public function getUrl() : string
284284
$url .= '@';
285285
}
286286
$url .= $this->getHost();
287-
$url .= $this->getPath();
287+
$url .= $this->getRelative();
288+
return $url;
289+
}
290+
291+
/**
292+
* Get the relative URL.
293+
*
294+
* @since 6.1
295+
*
296+
* @return string
297+
*/
298+
public function getRelative() : string
299+
{
300+
$relative = $this->getPath();
288301
$part = $this->getQuery();
289302
if ($part !== null) {
290-
$url .= '?' . $part;
303+
$relative .= '?' . $part;
291304
}
292305
$part = $this->getFragment();
293306
if ($part !== null) {
294-
$url .= '#' . $part;
307+
$relative .= '#' . $part;
295308
}
296-
return $url;
309+
return $relative;
297310
}
298311

299312
/**

tests/URLTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,34 @@ public function testSameUrl() : void
6565
self::assertSame($expected, $url->__toString());
6666
}
6767

68+
public function testRelative() : void
69+
{
70+
$url = 'http://domain.tld';
71+
$object = new URL($url);
72+
self::assertNotSame('', $object->getRelative());
73+
$url = 'http://domain.tld/';
74+
$object = new URL($url);
75+
self::assertSame('/', $object->getRelative());
76+
$url = 'http://domain.tld?foo=bar';
77+
$object = new URL($url);
78+
self::assertSame('/?foo=bar', $object->getRelative());
79+
$url = 'http://domain.tld/?foo=bar';
80+
$object = new URL($url);
81+
self::assertSame('/?foo=bar', $object->getRelative());
82+
$url = 'http://domain.tld#contact';
83+
$object = new URL($url);
84+
self::assertSame('/#contact', $object->getRelative());
85+
$url = 'http://domain.tld/?foo=bar#contact';
86+
$object = new URL($url);
87+
self::assertSame('/?foo=bar#contact', $object->getRelative());
88+
$url = 'http://domain.tld/foo/bar#contact';
89+
$object = new URL($url);
90+
self::assertSame('/foo/bar#contact', $object->getRelative());
91+
$url = 'http://domain.tld/foo/bar/#contact';
92+
$object = new URL($url);
93+
self::assertSame('/foo/bar/#contact', $object->getRelative());
94+
}
95+
6896
public function testPathEndsWithBar() : void
6997
{
7098
$url = 'http://domain.tld';

0 commit comments

Comments
 (0)