Completed
Push — master ( 51bd4b...f1ece3 )
by Joseph
02:11
created

Url   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 14
c 1
b 0
f 1
lcom 2
cbo 0
dl 0
loc 72
ccs 34
cts 34
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A findFirst() 0 8 2
A findAll() 0 9 2
A extract() 0 8 2
A parse() 0 10 2
B formatRelativeToAbsolute() 0 20 5
1
<?php
2
3
namespace Jclyons52\PagePreview;
4
5
class Url
6
{
7
    public $original;
8
    
9
    public $components;
10
    
11 54
    public function __construct($url)
12
    {
13 54
        $this->original = $url;
14 54
        $this->components = $this->parse($url);
15 51
    }
16
17 6
    public static function findFirst($text)
18
    {
19 6
        if ($urls = self::extract($text)) {
20 3
            return new self($urls[0]);
21
        }
22
        
23 3
        return null;
24
    }
25
    
26 6
    public static function findAll($text)
27
    {
28 6
        if ($urls = self::extract($text)) {
29 3
            return array_map(function ($url) {
30 3
                return new self($url);
31 3
            }, $urls);
32
        }
33 3
        return null;
34
    }
35
    
36 9
    public static function extract($text)
37
    {
38 9
        if (preg_match_all('!https?://\S+!', $text, $matches) === 0) {
39 3
            return null;
40
        }
41
        
42 6
        return $matches[0];
43
    }
44
    
45 54
    public function parse($url)
46
    {
47 54
        $urlComponents = parse_url($url);
48
49 54
        if (filter_var($url, FILTER_VALIDATE_URL) === false) {
50 3
            throw new \Exception("url {$url} is invalid");
51
        }
52
        
53 51
        return $urlComponents;
54
    }
55
    
56 36
    public function formatRelativeToAbsolute($url)
57
    {
58 36
        if (substr($url, 0, 5) === "data:") {
59 30
            return $url;
60
        }
61
62 36
        $path = array_key_exists('path', $this->components) ? $this->components['path'] : '';
63
64 36
        if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
65 36
            return $url;
66
        }
67 36
        if (substr($url, 0, 1) === '/') {
68 36
            return 'http://' . $this->components['host'] . $url;
69
        }
70
71 36
        $host = trim($this->components['host'], '/') . '/';
72 36
        $path = trim($path, '/') . '/';
73
74 36
        return 'http://' . $host . $path . $url;
75
    }
76
}
77