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

Url::extract()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
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