Skip to content

Commit 571c697

Browse files
authored
Merge pull request #2 from domainvalidity/2.x
Validate that the host is valid
2 parents e0f4f7b + 0a8312d commit 571c697

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

src/Host/Host.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ public function __construct(
1111
public ?string $host = null,
1212
public ?string $domain = null,
1313
public ?string $tld = null,
14+
private ?bool $isValid = null,
1415
public ?bool $isPrivate = null,
1516
) {
16-
$parsed = HostParser::parse($this->original);
17+
$parsed = HostParser::parse(strtolower($this->original));
1718

1819
$this->host = strval($parsed['host']);
1920
}
@@ -38,6 +39,11 @@ public function tld(?string $tld = null): string|self
3839
$this->tld = $tld;
3940

4041
$root = str_replace(strval($this->tld), '', strval($this->host));
42+
43+
if (!validate_domain_root(trim($root, '.'))) {
44+
$this->isValid = false;
45+
}
46+
4147
$root = explode('.', trim(strval($root), '.'));
4248

4349
$this->domain(end($root) . '.' . $this->tld);
@@ -58,7 +64,7 @@ public function domain(?string $domain = null): string|self
5864

5965
public function isValid(): bool
6066
{
61-
return !empty($this->tld());
67+
return $this->isValid ?? !empty($this->tld());
6268
}
6369

6470
public function isPrivate(?bool $isPrivate = null): bool|self

src/functions.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,9 @@ function remove_empty_lines(string $text): ?string
2323

2424
return $text;
2525
}
26+
27+
function validate_domain_root(string $root): bool
28+
{
29+
// Check if the string only contains alphanumeric values, dots or dashes
30+
return preg_match('/^[a-zA-Z0-9.-]+$/', $root) === 1;
31+
}

tests/Unit/ValidatorTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,13 @@
5252
it('empty domain', fn () => expect($host->domain())->toBe(''));
5353
it("is same as $url", fn () => expect($host->original())->toBe($url));
5454
});
55+
56+
describe('Invalid *.adro.com', function () {
57+
$validator = getInstance();
58+
$url = 'https://*.adro.com';
59+
$host = $validator->validate($url);
60+
61+
it('is not a valid domain', fn () => expect($host->isValid())->toBeFalse());
62+
it('is not empty domain', fn () => expect($host->domain())->toBe('adro.com'));
63+
it("is same as $url", fn () => expect($host->original())->toBe($url));
64+
});

0 commit comments

Comments
 (0)