Completed
Push — master ( 9d0a53...ecd7bc )
by Maik
01:48
created

UrlParser   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 12
c 7
b 0
f 0
lcom 0
cbo 3
dl 0
loc 68
ccs 0
cts 37
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C parseUrl() 0 28 8
A getPortByScheme() 0 18 4
1
<?php
2
3
/**
4
 * This file is part of the PHP Generics package.
5
 *
6
 * @package Generics
7
 */
8
namespace Generics\Util;
9
10
use Generics\Socket\InvalidUrlException;
11
use Generics\Socket\Url;
12
13
/**
14
 * This class provides a parser to retrieve Url objects out of arbitrary URIs
15
 *
16
 * @author Maik Greubel <[email protected]>
17
 */
18
class UrlParser
19
{
20
21
    /**
22
     * Parse a URI into a Url
23
     *
24
     * @param string $url
25
     * @throws InvalidUrlException
26
     * @return \Generics\Socket\Url
27
     */
28
    public static function parseUrl($url): Url
29
    {
30
        $parts = parse_url($url);
31
        
32
        if (false === $parts || false === Arrays::hasElement($parts, 'host') || false === Arrays::hasElement($parts, 'scheme')) {
33
            throw new InvalidUrlException('The URL {url} does not contain necessary parts', array('url' => $url));
34
        }
35
        
36
        $address = $parts['host'];
37
        $scheme = $parts['scheme'];
38
        $query = (isset($parts['query']) ? $parts['query'] : '');
39
        $port = 0;
40
        $path = "/";
41
        
42
        if (isset($parts['port'])) {
43
            $port = intval($parts['port']);
44
        }
45
        
46
        if ($port == 0) {
47
            $port = self::getPortByScheme($scheme);
48
        }
49
        
50
        if (isset($parts['path'])) {
51
            $path = $parts['path'];
52
        }
53
        
54
        return new Url($address, $port, $path, $scheme, $query);
55
    }
56
57
    /**
58
     * Get port number by scheme name.
59
     * The port will be the default which is defined by
60
     * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
61
     *
62
     * @param string $scheme
63
     *            The scheme.
64
     * @throws InvalidUrlException
65
     * @return int
66
     */
67
    public static function getPortByScheme($scheme): int
68
    {
69
        switch ($scheme) {
70
            case 'http':
71
                return 80;
72
            
73
            case 'https':
74
                return 443;
75
            
76
            case 'ftp':
77
                return 21;
78
            
79
            default:
80
                throw new InvalidUrlException("Scheme {scheme} is not handled!", array(
81
                    'scheme' => $scheme
82
                ));
83
        }
84
    }
85
}
86