diff --git a/src/HTTP/Requests/WithURL.php b/src/HTTP/Requests/WithURL.php --- a/src/HTTP/Requests/WithURL.php +++ b/src/HTTP/Requests/WithURL.php @@ -2,6 +2,7 @@ namespace Keruald\OmniTools\HTTP\Requests; +use Keruald\OmniTools\HTTP\URL; use Keruald\OmniTools\Strings\Multibyte\StringUtilities; trait WithURL { @@ -84,4 +85,18 @@ ]; } + /** + * Create a URL object, using the current request server URL for protocol + * and domain name. + * + * @param string $query The query part of the URL [facultative] + * @param int $encodeMode Encoding to use for the query [facultative] + */ + public static function createLocalURL (string $query = "", + int $encodeMode = URL::ENCODE_RFC3986_SLASH_EXCEPTED + ) : URL { + return (new URL(self::getServerURL())) + ->setQuery($query, $encodeMode); + } + } diff --git a/tests/HTTP/Requests/RequestTest.php b/tests/HTTP/Requests/RequestTest.php --- a/tests/HTTP/Requests/RequestTest.php +++ b/tests/HTTP/Requests/RequestTest.php @@ -79,6 +79,24 @@ $this->assertEquals($url, Request::getServerURL()); } + /** + * @backupGlobals enabled + * @dataProvider provideServerURLs + */ + public function testCreateLocalURL (array $server, string $url) : void { + $_SERVER = $server; + + $this->assertEquals( + $url . "/", + Request::createLocalURL()->__toString() + ); + + $this->assertEquals( + $url . "/foo", + Request::createLocalURL("foo")->__toString() + ); + } + /// /// Data providers ///