diff --git a/lib/Request.php b/lib/Request.php index 99a13d2..c0ab31c 100644 --- a/lib/Request.php +++ b/lib/Request.php @@ -110,10 +110,17 @@ public function setAbsoluteUrl(string $url) public function getAbsoluteUrl(): string { if (!$this->absoluteUrl) { - // Guessing we're a http endpoint. - $this->absoluteUrl = 'http://'. - ($this->getHeader('Host') ?? 'localhost'). - $this->getUrl(); + $url = $this->getUrl(); + if (parse_url($url, PHP_URL_SCHEME)) { + // It's already an absolute URL + $this->absoluteUrl = $url; + } else { + $host = $this->getHeader('Host') + ?? parse_url($url, PHP_URL_HOST) + ?? 'localhost'; + // Guessing we're a http endpoint. + $this->absoluteUrl = "http://$host$url"; + } } return $this->absoluteUrl; diff --git a/tests/HTTP/RequestTest.php b/tests/HTTP/RequestTest.php index a810900..e432a78 100644 --- a/tests/HTTP/RequestTest.php +++ b/tests/HTTP/RequestTest.php @@ -134,4 +134,18 @@ public function testToStringAuthorization() .'foo'; $this->assertEquals($expected, (string) $request); } + + public function testAbsoluteUrlHttp(): void + { + $request = new Request('GET', 'http://example.com/foo/bar?a=b&c=d'); + self::assertEquals('http://example.com/foo/bar?a=b&c=d', $request->getAbsoluteUrl()); + } + + public function testAbsoluteUrlHttpHostPrevalence(): void + { + $request = new Request('GET', 'http://example.com/foo/bar?a=b&c=d', [ + 'Host' => 'example.org', + ]); + self::assertEquals('http://example.com/foo/bar?a=b&c=d', $request->getAbsoluteUrl()); + } }