From 7a01845db8e6d285753a5f80578037539ec2602d Mon Sep 17 00:00:00 2001 From: kenjis Date: Fri, 17 Feb 2023 08:58:14 +0900 Subject: [PATCH] feat: add param $host to constructor --- system/HTTP/SiteURI.php | 16 +++++++++++++++- tests/system/HTTP/SiteURITest.php | 12 ++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/system/HTTP/SiteURI.php b/system/HTTP/SiteURI.php index 44f819ea8f43..372d3939eb15 100644 --- a/system/HTTP/SiteURI.php +++ b/system/HTTP/SiteURI.php @@ -73,8 +73,10 @@ class SiteURI extends URI /** * @param string $relativePath URI path relative to baseURL. May include * queries or fragments. + * @param string $host Hostname. If it is not in $allowedHostnames, + * just be ignored. */ - public function __construct(App $configApp, string $relativePath = '') + public function __construct(App $configApp, string $relativePath = '', string $host = '') { $this->baseURL = $this->normalizeBaseURL($configApp); $this->indexPage = $configApp->indexPage; @@ -97,21 +99,33 @@ public function __construct(App $configApp, string $relativePath = '') $tempUri = $this->baseURL . $indexPage . $relativePath; $uri = new URI($tempUri); + // Update scheme if ($configApp->forceGlobalSecureRequests) { $uri->setScheme('https'); } + // Update host + if ($host !== '' && $this->checkHost($host, $configApp->allowedHostnames)) { + $uri->setHost($host); + } + $parts = parse_url((string) $uri); if ($parts === false) { throw HTTPException::forUnableToParseURI($uri); } $this->applyParts($parts); + // Set routePath $parts = explode('?', $relativePath); $routePath = $parts[0]; $this->setRoutePath($routePath); } + private function checkHost(string $host, array $allowedHostnames): bool + { + return (bool) (in_array($host, $allowedHostnames, true)); + } + private function normalizeBaseURL(App $configApp): string { // It's possible the user forgot a trailing slash on their diff --git a/tests/system/HTTP/SiteURITest.php b/tests/system/HTTP/SiteURITest.php index 74e035868196..413ab66ee57c 100644 --- a/tests/system/HTTP/SiteURITest.php +++ b/tests/system/HTTP/SiteURITest.php @@ -58,6 +58,18 @@ public function testConstructorRelativePathWithQuery() $this->assertSame('foo=1&bar=2', $uri->getQuery()); } + public function testConstructorHost() + { + $config = new App(); + $config->allowedHostnames = ['sub.example.com']; + + $uri = new SiteURI($config, '', 'sub.example.com'); + + $this->assertInstanceOf(SiteURI::class, $uri); + $this->assertSame('http://sub.example.com/index.php/', (string) $uri); + $this->assertSame('/index.php/', $uri->getPath()); + } + public function testConstructorSubfolder() { $config = new App();