UrlUtils::resolveRelativeUrl()   C
last analyzed

Complexity

Conditions 12
Paths 35

Size

Total Lines 61
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 61
rs 6.2855
cc 12
eloc 27
nc 35
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Goetas\XML\XSDReader\Utils;
3
4
class UrlUtils
5
{
6
7
    public static function resolveRelativeUrl($base, $rel)
8
    {
9
        $re = array(
10
            '#(/\.?/)#',
11
            '#/(?!\.\.)[^/]+/\.\./#'
12
        );
13
14
15
        if (!$rel) {
16
            return $base;
17
        }
18
19
        /* return if already absolute URL */
20
        if (parse_url($rel, PHP_URL_SCHEME) !== null || substr($rel, 0, 2) === '//') {
21
            return $rel;
22
        }
23
24
        /* queries and anchors */
25
        if ($rel[0] === '#' || $rel[0] === '?') {
26
            return $base.$rel;
27
        }
28
29
        /*
30
         * parse base URL and convert to local variables:
31
         * $scheme, $host, $path
32
         */
33
        $parts = parse_url($base);
34
35
        /* remove non-directory element from path */
36
        $path = isset($parts['path']) ? preg_replace('#/[^/]*$#', '', $parts["path"]) : '';
37
38
        /* destroy path if relative url points to root */
39
        if ($rel[0] === '/') {
40
            $path = '';
41
        }
42
43
        /* Build absolute URL */
44
        $abs = '';
45
46
        if (isset($parts["host"])) {
47
            $abs .= $parts['host'];
48
        }
49
50
        if (isset($parts["port"])) {
51
            $abs .= ":".$parts["port"];
52
        }
53
54
        $abs .= $path."/".$rel;
55
56
        /* replace '//' or '/./' or '/foo/../' with '/' */
57
        $n = 1;
58
        do {
59
            $abs = preg_replace($re, '/', $abs, -1, $n);
60
        } while ($n > 0);
61
62
        if (isset($parts["scheme"])) {
63
            $abs = $parts["scheme"].'://'.$abs;
64
        }
65
66
        return $abs;
67
    }
68
69
}
70