UriValidator::validate()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 10
rs 9.2
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace AlgoWeb\xsdTypes\AxillaryClasses;
4
5
class UriValidator
6
{
7
    const URI_REGEXP = '/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#?(.*))?/';
8
9
    /**
10
     * Validate a URI according to RFC 3986 (+errata)
11
     * (See: http://www.rfc-editor.org/errata_search.php?rfc=3986).
12
     *
13
     * @param string $uri the URI to validate
14
     *
15
     * @return bool TRUE when the URI is valid, FALSE when invalid
16
     */
17
    public static function validate($uri)
18
    {
19
        if (substr_count($uri, '#') > 1 || !self::checkHexDigits($uri)) {
20
            return false;
21
        }
22
        if (filter_var($uri, FILTER_VALIDATE_URL) !== false) {
23
            return true;
24
        }
25
        return (bool)preg_match(self::URI_REGEXP, $uri);
26
    }
27
28
    private static function checkHexDigits($uri)
29
    {
30
        $lastPos = 0;
31
        while (($lastPos = strpos($uri, '%', $lastPos)) !== false) {
32
            if (!(ctype_xdigit($uri[$lastPos + 1]) && ctype_xdigit($uri[$lastPos + 2]))) {
33
                return false;
34
            }
35
            $lastPos = $lastPos + strlen('%');
36
        }
37
        return true;
38
    }
39
}
40