1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TraderInteractive\Filter; |
4
|
|
|
|
5
|
|
|
use TraderInteractive\Exceptions\FilterException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* A collection of filters for urls. |
9
|
|
|
*/ |
10
|
|
|
final class Url |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Filter an url |
14
|
|
|
* |
15
|
|
|
* Filters value as URL (according to » http://www.faqs.org/rfcs/rfc2396) |
16
|
|
|
* |
17
|
|
|
* The return value is the url, as expected by the \TraderInteractive\Filterer class. |
18
|
|
|
* By default, nulls are not allowed. |
19
|
|
|
* |
20
|
|
|
* @param mixed $value The value to filter. |
21
|
|
|
* @param bool $allowNull True to allow nulls through, and false (default) if nulls should not be allowed. |
22
|
|
|
* |
23
|
|
|
* @return string|null The passed in $value. |
24
|
|
|
* |
25
|
|
|
* @throws FilterException if the value did not pass validation. |
26
|
|
|
*/ |
27
|
|
|
public static function filter($value = null, bool $allowNull = false) |
28
|
|
|
{ |
29
|
|
|
if (self::valueIsNullAndValid($allowNull, $value)) { |
30
|
|
|
return null; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
self::validateString($value); |
34
|
|
|
|
35
|
|
|
return self::filterUrl($value); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
private static function filterUrl(string $value = null) : string |
39
|
|
|
{ |
40
|
|
|
$filteredUrl = filter_var($value, FILTER_VALIDATE_URL); |
41
|
|
|
if ($filteredUrl === false) { |
42
|
|
|
throw new FilterException("Value '{$value}' is not a valid url"); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $filteredUrl; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private static function valueIsNullAndValid(bool $allowNull, $value = null) : bool |
49
|
|
|
{ |
50
|
|
|
if ($allowNull === false && $value === null) { |
51
|
|
|
throw new FilterException('Value failed filtering, $allowNull is set to false'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $allowNull === true && $value === null; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private static function validateString($value) |
58
|
|
|
{ |
59
|
|
|
if (!is_string($value)) { |
60
|
|
|
throw new FilterException("Value '" . var_export($value, true) . "' is not a string"); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|