From 40d7dcd46e72e14238d9860773cea4b825e54dbf Mon Sep 17 00:00:00 2001 From: otsch Date: Tue, 11 Oct 2022 01:18:39 +0200 Subject: [PATCH] Fix getting subdomain of URLs without subdomain When a URL doesn't contain a subdomain part, the `subdomain()` method returns `null`. This previously returned the whole domain (/host) which was wrong/unwanted behaviour. --- CHANGELOG.md | 4 ++++ src/Host.php | 5 ++++- tests/HostTest.php | 11 +++++++++++ tests/UrlTest.php | 7 +++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d06f51..ba93688 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.0.1] - 2022-10-11 +### Fixed +- When a URL doesn't contain a subdomain part, the `subdomain()` method returns `null`. + ## [2.0.0] - 2022-09-15 ### Removed - BREAKING: Removed access to URL components (scheme, host, path,...) via magic class properties (`$this->scheme`, `$this->host`,...). Use method calls instead (`$this->scheme()`, `$this->host()`,...). diff --git a/src/Host.php b/src/Host.php index 378de35..35d14bf 100644 --- a/src/Host.php +++ b/src/Host.php @@ -27,7 +27,10 @@ public function __construct(string $host) if ($domainSuffix) { $this->domain = new Domain($this->host, $domainSuffix); - $this->subdomain = Helpers::stripFromEnd($this->host, '.' . $this->domain); + + if ($this->host !== (string) $this->domain) { + $this->subdomain = Helpers::stripFromEnd($this->host, '.' . $this->domain); + } } } diff --git a/tests/HostTest.php b/tests/HostTest.php index 1dec468..74b4c43 100644 --- a/tests/HostTest.php +++ b/tests/HostTest.php @@ -49,6 +49,17 @@ public function testSubdomain(): void $this->assertEquals('foo.bar.yololo.example.com', $host->__toString()); } + public function testEmptySubdomain(): void + { + $host = new Host('crwlr.software'); + + $this->assertNull($host->subdomain()); + + $host = new Host('www.crwlr.software'); + + $this->assertEquals('www', $host->subdomain()); + } + public function testDomain(): void { $host = new Host('www.example.com'); diff --git a/tests/UrlTest.php b/tests/UrlTest.php index 13aaa5c..03128ca 100644 --- a/tests/UrlTest.php +++ b/tests/UrlTest.php @@ -412,6 +412,13 @@ public function testReplaceSubdomain(): void ); } + public function testEmptySubdomain(): void + { + $this->assertNull(Url::parse('https://crwlr.software')->subdomain()); + + $this->assertEquals('www', Url::parse('https://www.crwlr.software')->subdomain()); + } + /** * @throws InvalidUrlComponentException * @throws Exception