Completed
Push — master ( 9f08bd...d4c5d1 )
by Jan-Petter
06:45 queued 10s
created

UrlParser::urlValidateScheme()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
namespace vipnytt\SitemapParser;
3
4
/**
5
 * Trait UrlParser
6
 *
7
 * @package vipnytt\SitemapParser
8
 */
9
trait UrlParser
10
{
11
    /**
12
     * URL encoder according to RFC 3986
13
     * Returns a string containing the encoded URL with disallowed characters converted to their percentage encodings.
14
     * @link http://publicmind.in/blog/url-encoding/
15
     *
16
     * @param string $url
17
     * @return string
18
     */
19
    protected function urlEncode($url)
20
    {
21
        $reserved = [
22
            ":" => '!%3A!ui',
23
            "/" => '!%2F!ui',
24
            "?" => '!%3F!ui',
25
            "#" => '!%23!ui',
26
            "[" => '!%5B!ui',
27
            "]" => '!%5D!ui',
28
            "@" => '!%40!ui',
29
            "!" => '!%21!ui',
30
            "$" => '!%24!ui',
31
            "&" => '!%26!ui',
32
            "'" => '!%27!ui',
33
            "(" => '!%28!ui',
34
            ")" => '!%29!ui',
35
            "*" => '!%2A!ui',
36
            "+" => '!%2B!ui',
37
            "," => '!%2C!ui',
38
            ";" => '!%3B!ui',
39
            "=" => '!%3D!ui',
40
            "%" => '!%25!ui'
41
        ];
42
        return preg_replace(array_values($reserved), array_keys($reserved), rawurlencode($url));
43
    }
44
45
    /**
46
     * Validate URL
47
     *
48
     * @param string $url
49
     * @return bool
50
     */
51
    protected function urlValidate($url)
52
    {
53
        return (
54
            filter_var($url, FILTER_VALIDATE_URL) &&
55
            ($parsed = parse_url($url)) !== false &&
56
            $this->urlValidateHost($parsed['host']) &&
57
            $this->urlValidateScheme($parsed['scheme'])
58
        );
59
    }
60
61
    /**
62
     * Validate host name
63
     *
64
     * @link http://stackoverflow.com/questions/1755144/how-to-validate-domain-name-in-php
65
     *
66
     * @param  string $host
67
     * @return bool
68
     */
69
    protected static function urlValidateHost($host)
70
    {
71
        return (
72
            preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $host) //valid chars check
73
            && preg_match("/^.{1,253}$/", $host) //overall length check
74
            && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $host) //length of each label
75
        );
76
    }
77
78
    /**
79
     * Validate URL scheme
80
     *
81
     * @param  string $scheme
82
     * @return bool
83
     */
84
    protected static function urlValidateScheme($scheme)
85
    {
86
        return in_array($scheme, [
87
                'http',
88
                'https',
89
            ]
90
        );
91
    }
92
}
93