UrlParser   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 3
dl 0
loc 68
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B 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 39
    public static function parseUrl($url): Url
29
    {
30 39
        $parts = parse_url($url);
31
        
32 39
        if (false === $parts || false === Arrays::hasElement($parts, 'host') || false === Arrays::hasElement($parts, 'scheme')) {
33 37
            throw new InvalidUrlException('The URL {url} does not contain necessary parts', array('url' => $url));
34
        }
35
        
36 25
        $address = $parts['host'];
37 25
        $scheme = $parts['scheme'];
38 25
        $query = (isset($parts['query']) ? $parts['query'] : '');
39 25
        $port = 0;
40 25
        $path = "/";
41
        
42 25
        if (isset($parts['port'])) {
43 2
            $port = intval($parts['port']);
44
        }
45
        
46 25
        if ($port == 0) {
47 23
            $port = self::getPortByScheme($scheme);
48
        }
49
        
50 23
        if (isset($parts['path'])) {
51 20
            $path = $parts['path'];
52
        }
53
        
54 23
        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 23
    public static function getPortByScheme($scheme): int
68
    {
69
        switch ($scheme) {
70 23
            case 'http':
71 10
                return 80;
72
            
73 13
            case 'https':
74 9
                return 443;
75
            
76 4
            case 'ftp':
77 2
                return 21;
78
            
79
            default:
80 2
                throw new InvalidUrlException("Scheme {scheme} is not handled!", array(
81 2
                    'scheme' => $scheme
82
                ));
83
        }
84
    }
85
}
86