diff --git a/src/Validator/URL.php b/src/Validator/URL.php index 1c12008..bb26568 100644 --- a/src/Validator/URL.php +++ b/src/Validator/URL.php @@ -15,12 +15,16 @@ class URL extends Validator { protected array $allowedSchemes; + protected bool $allowEmpty; + /** * @param array $allowedSchemes + * @param bool $allowEmpty */ - public function __construct(array $allowedSchemes = []) + public function __construct(array $allowedSchemes = [], bool $allowEmpty = false) { $this->allowedSchemes = $allowedSchemes; + $this->allowEmpty = $allowEmpty; } /** @@ -49,6 +53,10 @@ public function getDescription(): string */ public function isValid($value): bool { + if ($this->allowEmpty && $value === '') { + return true; + } + if (\filter_var($value, FILTER_VALIDATE_URL) === false) { return false; } diff --git a/tests/Validator/URLTest.php b/tests/Validator/URLTest.php index ddf52df..d7d010e 100644 --- a/tests/Validator/URLTest.php +++ b/tests/Validator/URLTest.php @@ -52,4 +52,16 @@ public function testIsValidAllowedSchemes(): void $this->assertSame(true, $this->url->isValid('https://example.com')); $this->assertSame(false, $this->url->isValid('gopher://www.example.com')); } + + public function testAllowEmpty(): void + { + $urlAllowEmpty = new URL([], true); + $this->assertSame(true, $urlAllowEmpty->isValid('')); + $this->assertSame(false, $urlAllowEmpty->isValid(null)); + $this->assertSame(true, $urlAllowEmpty->isValid('https://example.com')); + $this->assertSame(false, $urlAllowEmpty->isValid('not-a-url')); + + $this->assertSame(false, $this->url->isValid('')); + $this->assertSame(false, $this->url->isValid(null)); + } }