Skip to content

Commit 9502132

Browse files
authored
Merge pull request #73 from kgun1212/master
Allow Null for URL Filter
2 parents 97d42e1 + a8bd0fc commit 9502132

3 files changed

Lines changed: 45 additions & 2 deletions

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ assert($value === ['abc', 'def', 'ghi']);
214214

215215
#### Url::filter
216216
Aliased in the filterer as `url`, this filter verifies that the argument is a URL string according to
217-
[RFC2396](http://www.faqs.org/rfcs/rfc2396).
217+
[RFC2396](http://www.faqs.org/rfcs/rfc2396). The second parameter can be set to `true` to allow
218+
null values through without an error (they will stay null and not get converted to false).
218219

219220
The following checks that `$value` is a URL.
220221
```php

src/Filter/Url.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,26 @@ final class Url
1616
* Filters value as URL (according to » http://www.faqs.org/rfcs/rfc2396)
1717
*
1818
* The return value is the url, as expected by the \DominionEnterprises\Filterer class.
19+
* By default, nulls are not allowed.
1920
*
2021
* @param mixed $value The value to filter.
22+
* @param bool $allowNull True to allow nulls through, and false (default) if nulls should not be allowed.
2123
*
2224
* @return string The passed in $value.
2325
*
2426
* @throws \Exception if the value did not pass validation.
27+
* @throws \InvalidArgumentException if one of the parameters was not correctly typed.
2528
*/
26-
public static function filter($value)
29+
public static function filter($value, $allowNull = false)
2730
{
31+
if ($allowNull !== false && $allowNull !== true) {
32+
throw new \InvalidArgumentException('$allowNull was not a boolean value');
33+
}
34+
35+
if ($allowNull === true && $value === null) {
36+
return null;
37+
}
38+
2839
if (!is_string($value)) {
2940
throw new \Exception("Value '" . var_export($value, true) . "' is not a string");
3041
}

tests/Filter/UrlTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,35 @@ public function filterNotValid()
3737
{
3838
Url::filter('www.example.com');
3939
}
40+
41+
/**
42+
* @test
43+
* @covers ::filter
44+
*/
45+
public function filterNullPass()
46+
{
47+
$this->assertSame(null, Url::filter(null, true));
48+
}
49+
50+
/**
51+
* @test
52+
* @expectedException Exception
53+
* @expectedExceptionMessage Value 'NULL' is not a string
54+
* @covers ::filter
55+
*/
56+
public function filterNullFail()
57+
{
58+
Url::filter(null);
59+
}
60+
61+
/**
62+
* @test
63+
* @expectedException InvalidArgumentException
64+
* @expectedExceptionMessage $allowNull was not a boolean value
65+
* @covers ::filter
66+
*/
67+
public function filterAllowNullNotBoolean()
68+
{
69+
Url::filter('a', 5);
70+
}
4071
}

0 commit comments

Comments
 (0)