Skip to content

Commit

Permalink
Fix getting subdomain of URLs without subdomain
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
otsch committed Oct 10, 2022
1 parent 6cd1e1b commit 40d7dcd
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`,...).
Expand Down
5 changes: 4 additions & 1 deletion src/Host.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions tests/HostTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
7 changes: 7 additions & 0 deletions tests/UrlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 40d7dcd

Please sign in to comment.