From ab142c0bc1133f454b49c55cf304f9f5b18be608 Mon Sep 17 00:00:00 2001 From: Oluwatobi Date: Thu, 24 Aug 2023 00:04:23 +0300 Subject: [PATCH] fix: Remove question mark from url if there's no query --- src/Url.php | 6 +++--- tests/UrlTest.php | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Url.php b/src/Url.php index 474ca78..e4ec066 100644 --- a/src/Url.php +++ b/src/Url.php @@ -85,7 +85,7 @@ public function __toString(): string public function toString(): string { - return implode($this->toArray()); + return implode(array_filter($this->toArray())); } public function toArray(): array @@ -94,7 +94,7 @@ public function toArray(): array return [ $this->fullDomain, $this->path, - '?', + $this->query ? '?' : '', http_build_query($this->query), ]; } @@ -104,7 +104,7 @@ public function toArray(): array $this->domain, $this->port ? ':' . $this->port : $this->port, $this->path, - '?', + $this->query ? '?' : '', http_build_query($this->query) ]; } diff --git a/tests/UrlTest.php b/tests/UrlTest.php index 33f9431..82a56ac 100644 --- a/tests/UrlTest.php +++ b/tests/UrlTest.php @@ -74,6 +74,23 @@ public function testUrlIsCorrectForSetFullDomain(): void $this->assertEquals('http://localhost:8080/api/hello?name=John&public=yes', (string) $url); } + public function testUrlIsCorrectWhenThereIsNoQuery(): void + { + $url = Url::make( + fullDomain: 'http://localhost:8080', + path: '/api/hello', + ); + + $this->assertEquals([ + 'http://localhost:8080', + '/api/hello', + '', + '', + ], $url->toArray()); + + $this->assertEquals('http://localhost:8080/api/hello', (string) $url); + } + public function testUrlIsCorrectWhenSetOnConstructor(): void { $url = Url::make(