Skip to content

Commit db4969b

Browse files
authored
Merge pull request #257 from skjnldsv/patch-1
fix(request): properly compute absolute url
2 parents 0d7f23d + 66bc794 commit db4969b

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

lib/Request.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,17 @@ public function setAbsoluteUrl(string $url): void
109109
public function getAbsoluteUrl(): string
110110
{
111111
if ((null === $this->absoluteUrl) || ('' === $this->absoluteUrl)) {
112-
// Guessing we're a http endpoint.
113-
$this->absoluteUrl = 'http://'.
114-
($this->getHeader('Host') ?? 'localhost').
115-
$this->getUrl();
112+
$url = $this->getUrl();
113+
if (parse_url($url, PHP_URL_SCHEME)) {
114+
// It's already an absolute URL
115+
$this->absoluteUrl = $url;
116+
} else {
117+
$host = $this->getHeader('Host')
118+
?? parse_url($url, PHP_URL_HOST)
119+
?? 'localhost';
120+
// Guessing we're a http endpoint.
121+
$this->absoluteUrl = "http://$host$url";
122+
}
116123
}
117124

118125
return $this->absoluteUrl;

tests/HTTP/RequestTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,18 @@ public function testToStringAuthorization(): void
134134
.'foo';
135135
self::assertEquals($expected, (string) $request);
136136
}
137+
138+
public function testAbsoluteUrlHttp(): void
139+
{
140+
$request = new Request('GET', 'http://example.com/foo/bar?a=b&c=d');
141+
self::assertEquals('http://example.com/foo/bar?a=b&c=d', $request->getAbsoluteUrl());
142+
}
143+
144+
public function testAbsoluteUrlHttpHostPrevalence(): void
145+
{
146+
$request = new Request('GET', 'http://example.com/foo/bar?a=b&c=d', [
147+
'Host' => 'example.org',
148+
]);
149+
self::assertEquals('http://example.com/foo/bar?a=b&c=d', $request->getAbsoluteUrl());
150+
}
137151
}

0 commit comments

Comments
 (0)