diff --git a/src/Validator/Domain.php b/src/Validator/Domain.php index 535b681..9766263 100644 --- a/src/Validator/Domain.php +++ b/src/Validator/Domain.php @@ -18,7 +18,8 @@ class Domain extends Validator */ public function __construct( protected array $restrictions = [], - protected bool $hostnames = true + protected bool $hostnames = true, + protected bool $allowEmpty = false ) { } @@ -64,6 +65,10 @@ public function getDescription(): string */ public function isValid($value): bool { + if ($this->allowEmpty && $value === '') { + return true; + } + if (empty($value)) { return false; } diff --git a/tests/Validator/DomainTest.php b/tests/Validator/DomainTest.php index 9ec30c8..ecd25fc 100644 --- a/tests/Validator/DomainTest.php +++ b/tests/Validator/DomainTest.php @@ -120,6 +120,30 @@ public function testInvalidDomainsWithHostnamesFalse() $this->assertSame(true, $permissiveValidator->isValid('example.com/path')); // Path } + /** + * Test allowEmpty parameter + */ + public function testAllowEmpty() + { + // By default, empty string is invalid + $this->assertSame(false, $this->domain->isValid('')); + + // With allowEmpty=true, empty string is valid + $domainAllowEmpty = new Domain([], true, true); + $this->assertSame(true, $domainAllowEmpty->isValid('')); + + // null is still invalid even with allowEmpty=true + $this->assertSame(false, $domainAllowEmpty->isValid(null)); + + // Valid domains still pass with allowEmpty=true + $this->assertSame(true, $domainAllowEmpty->isValid('example.com')); + $this->assertSame(true, $domainAllowEmpty->isValid('subdomain.example.com')); + + // Invalid domains still fail with allowEmpty=true + $this->assertSame(false, $domainAllowEmpty->isValid('invalid..domain')); + $this->assertSame(false, $domainAllowEmpty->isValid(1)); + } + public function testRestrictions() { $validator = new Domain([