Passed
Push — master ( 9e19cf...b74b72 )
by Denis
03:40
created

Link::normalize()   C

Complexity

Conditions 11
Paths 16

Size

Total Lines 43
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 28
nc 16
nop 2
dl 0
loc 43
c 0
b 0
f 0
cc 11
rs 5.2653

How to fix   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
/**
3
 * @author: Denis Beliaev
4
 */
5
6
namespace DenisBeliaev\SitemapParser;
7
8
/**
9
 * Class Link
10
 * @package DenisBeliaev\SitemapParser
11
 */
12
class Link
13
{
14
    static function normalize($link, $base)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
15
    {
16
        if (substr($link, 0, 2) == '<a' && substr($link, -4, 4) == '</a>') {
17
            preg_match('~href=[\'"](.*?)[\'"]~i', $link, $matches);
18
            $link = $matches[1] ?? '';
19
        }
20
21
        $link = urldecode($link);
22
        $link = explode('#', $link)[0];
23
24
        if (empty($link)) {
25
            return '';
26
        }
27
28
        if (preg_match('~^mailto:|tel:.*~i', $link)) {
29
            return '';
30
        } elseif (preg_match('~^https?://[^/].*~i', $link)) {
31
            return $link;
32
        }
33
34
        $isProtocolRelative = preg_match('~^//[^/].*~', $link);
35
36
        $isSiteRelative = preg_match('~^/[^/].*~', $link);
37
        $isMainPage = $link == '/';
38
39
        $components = parse_url($base);
40
        if (empty($components['scheme']) || empty($components['host'])) {
41
            throw new \InvalidArgumentException('Wrong base value');
42
        }
43
        $scheme = $components['scheme'];
44
        $host = $components['host'];
45
46
        if ($isMainPage) {
47
            $link = $scheme . '://' . $host;
48
        } elseif ($isProtocolRelative) {
49
            $link = $scheme . ':' . $link;
50
        } elseif ($isSiteRelative) {
51
            $link = $scheme . '://' . $host . $link;
52
        } else {
53
            $link = $base . '/' . $link;
54
        }
55
56
        return $link;
57
    }
58
}