UrlParser::urlEncode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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