Completed
Push — master ( d3a461...325afc )
by Felix
02:00
created

Url::getHash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Felix\Scraper;
4
5
class Url
6
{
7
    /** @var string */
8
    protected $url;
9
10
    /** @var array */
11
    protected $parts;
12
13
    /** @var string */
14
    protected $hash;
15
16 5
    public function __construct($url)
17
    {
18 5
        $this->setParts($url);
19 5
    }
20
21 2
    public function __toString()
22
    {
23 2
        return $this->url;
24
    }
25
26
    /**
27
     * Parsear URL.
28
     *
29
     * @param $url string Toda la url.
30
     *
31
     * @return void
32
     */
33 5
    public function setParts($url)
34
    {
35 5
        $parts = parse_url($url);
36
37 5
        if ($parts === false) {
38
            throw new \Exception($url.' es una URL mal formada y no se puede procesar');
39
        }
40
41 5
        $this->url = $url;
42 5
        $this->parts = $parts;
43 5
        $this->hash = md5($url);
44 5
    }
45
46
    /**
47
     * Retornar hash url.
48
     * 
49
     * @return string
50
     */
51 1
    public function getHash()
52
    {
53 1
        return $this->hash;
54
    }
55
56
    /**
57
     * Obtener una parte de la URL.
58
     *
59
     * @param $part string Parte de la URL (Ej: host).
60
     *
61
     * @return string|null
62
     */
63 3
    public function part($part)
64
    {
65 3
        return array_key_exists($part, $this->parts) ? $this->parts[$part] : null;
66
    }
67
68
    /**
69
     * Url tiene una parte.
70
     *
71
     * @return bool true|false
72
     */
73 2
    public function has($part)
74
    {
75 2
        return $this->part($part) !== null;
76
    }
77
78
    /**
79
     * Decodificación URL.
80
     *
81
     * @return object
82
     */
83 1
    public function decode()
84
    {
85 1
        $this->url = urldecode($this->url);
86
87 1
        return $this;
88
    }
89
90
    /**
91
     * Dada una URL, normaliza esa URL.
92
     *
93
     * @param $schemeAndHost string Esquema y dominio base (Ej. http://example.com)
94
     *
95
     * @return string
96
     */
97 1
    public function normalize($schemeAndHost)
98
    {
99 1
        if (!$this->has('host') || !$this->has('scheme')) {
100 1
            $this->url = $schemeAndHost.$this->url;
101
        }
102
103 1
        return $this;
104
    }
105
}
106