Passed
Push — master ( 707ddf...aa8b2f )
by Sebastian
04:56
created

URLInfo_Schemes::buildCache()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AppUtils;
6
7
/**
8
 * Class URLInfo_Schemes
9
 * @package AppUtils
10
 *
11
 * @link https://en.wikipedia.org/wiki/List_of_URI_schemes
12
 */
13
class URLInfo_Schemes
14
{
15
    /**
16
     * @var string[]
17
     */
18
    protected static $schemes = array(
19
        'http://',
20
        'https://',
21
        'mailto:',
22
        'tel:',
23
        'git://'
24
25
26
        /*
27
        'ftp://',
28
        'sftp://',
29
        'smb://',
30
        'sms:',
31
        'udp://',
32
        'vnc://',
33
        'xmpp:',
34
        'svn:',
35
        'svn+ssh:',
36
        'ssh://',
37
        'bitcoin:',
38
        'callto:',
39
        'chrome://',
40
        'dns://',
41
        'dns:',
42
        'ed2k://',
43
        'facetime://',
44
        'feed://',
45
        'feed:',
46
        'file://',
47
        'geo:',
48
        'ldap://',
49
        'ldaps://',
50
        'magnet:',
51
        'im:',
52
        'steam://',
53
        'steam:', // command line URI
54
        'telnet://',
55
        'teamspeak://'
56
        */
57
    );
58
59
    /**
60
     * @var array<string,int>
61
     */
62
    protected static $cache = array();
63
64
    /**
65
     * Tries to detect a valid scheme in the specified URL,
66
     * using the internal list of known schemes.
67
     *
68
     * @param string $url
69
     * @return string|null
70
     */
71
    public static function detectScheme(string $url) : ?string
72
    {
73
        self::buildCache();
74
75
        foreach(self::$cache as $scheme => $length) {
76
            if(strtolower(substr($url, 0, $length)) === $scheme) {
77
                return $scheme;
78
            }
79
        }
80
81
        return null;
82
    }
83
84
    /**
85
     * Stores the length of each scheme to avoid
86
     * doing this each time we want to detect a
87
     * scheme.
88
     */
89
    private static function buildCache() : void
90
    {
91
        if(!empty(self::$cache)) {
92
            return;
93
        }
94
95
        foreach(self::$schemes as $scheme) {
96
            self::$cache[$scheme] = strlen($scheme);
97
        }
98
    }
99
}
100