Skip to content

Commit 6cce9f7

Browse files
authored
Merge pull request #7 from utopia-php/copilot/add-empty-parameter-to-url-validator
Add `$allowEmpty` parameter to URL validator
2 parents 30b6030 + c2aa888 commit 6cce9f7

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/Validator/URL.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,16 @@ class URL extends Validator
1515
{
1616
protected array $allowedSchemes;
1717

18+
protected bool $allowEmpty;
19+
1820
/**
1921
* @param array $allowedSchemes
22+
* @param bool $allowEmpty
2023
*/
21-
public function __construct(array $allowedSchemes = [])
24+
public function __construct(array $allowedSchemes = [], bool $allowEmpty = false)
2225
{
2326
$this->allowedSchemes = $allowedSchemes;
27+
$this->allowEmpty = $allowEmpty;
2428
}
2529

2630
/**
@@ -49,6 +53,10 @@ public function getDescription(): string
4953
*/
5054
public function isValid($value): bool
5155
{
56+
if ($this->allowEmpty && $value === '') {
57+
return true;
58+
}
59+
5260
if (\filter_var($value, FILTER_VALIDATE_URL) === false) {
5361
return false;
5462
}

tests/Validator/URLTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,16 @@ public function testIsValidAllowedSchemes(): void
5252
$this->assertSame(true, $this->url->isValid('https://example.com'));
5353
$this->assertSame(false, $this->url->isValid('gopher://www.example.com'));
5454
}
55+
56+
public function testAllowEmpty(): void
57+
{
58+
$urlAllowEmpty = new URL([], true);
59+
$this->assertSame(true, $urlAllowEmpty->isValid(''));
60+
$this->assertSame(false, $urlAllowEmpty->isValid(null));
61+
$this->assertSame(true, $urlAllowEmpty->isValid('https://example.com'));
62+
$this->assertSame(false, $urlAllowEmpty->isValid('not-a-url'));
63+
64+
$this->assertSame(false, $this->url->isValid(''));
65+
$this->assertSame(false, $this->url->isValid(null));
66+
}
5567
}

0 commit comments

Comments
 (0)