Failed Conditions
Pull Request — master (#1)
by
unknown
02:11
created

Url::filter()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 5
nc 3
nop 2
dl 0
loc 11
rs 8.8571
c 0
b 0
f 0
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(string $value = null, bool $allowNull = false)
28
    {
29
        if ($allowNull === true && $value === null) {
30
            return null;
31
        }
32
33
        if ($allowNull === false && $value === null) {
34
            throw new FilterException('Value failed filtering, $allowNull is set to false');
35
        }
36
37
        return self::filterUrl($value);
38
    }
39
40
    private static function filterUrl(string $value = null) : string
41
    {
42
        $filteredUrl = filter_var($value, FILTER_VALIDATE_URL);
43
        if ($filteredUrl === false) {
44
            throw new FilterException("Value '{$value}' is not a valid url");
45
        }
46
47
        return $filteredUrl;
48
    }
49
}
50