Completed
Push — master ( adbff9...ee9799 )
by Felix
05:30 queued 23s
created

Url::has()   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 1
crap 1
1
<?php
2
3
namespace Felix\Scraper;
4
5
class Url
6
{
7
    /** @var string */
8
    private $url;
9
10
    /** @var array */
11
    private $parts;
12
13
    /** @var string */
14
    private $hash;
15
16 6
    public function __construct($url)
17
    {
18 6
        $this->setParts($url);
19 6
    }
20
21 1
    public function __toString()
22
    {
23 1
        return $this->url;
24
    }
25
26
    /**
27
     * Parsear URL.
28
     *
29
     * @param $url string Toda la url.
30
     *
31
     * @return void
32
     */
33 6
    public function setParts($url)
34
    {
35 6
        $parts = parse_url($url);
36
37 6
        if ($parts === false) {
38
            throw new \Exception($url.' es una URL mal formada y no se puede procesar');
39
        }
40
41 6
        $this->url = $url;
42 6
        $this->parts = $parts;
43 6
        $this->hash = md5($url);
44 6
    }
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 4
    public function part($part)
64
    {
65 4
        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 3
    public function has($part)
74
    {
75 3
        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
     * Agregar el esquema si no tiene.
92
     * 
93
     * @return string $url
94
     */
95 1
    public function addScheme()
96
    {
97 1
        if (!$this->has('scheme')) {
98 1
            $this->url = "http://" . ltrim($this->url, '/');
99
        }
100
101 1
        return $this->url;
102
    }
103
104
    /**
105
     * Dada una URL, normaliza esa URL.
106
     *
107
     * @param $schemeAndHost string Esquema y dominio base (Ej. http://example.com)
108
     *
109
     * @return string
110
     */
111 1
    public function normalize($schemeAndHost)
112
    {
113 1
        if (!$this->has('host') || !$this->has('scheme')) {
114 1
            $this->url = rtrim($schemeAndHost, '/').'/'.ltrim($this->url, '/');
115
        }
116
117 1
        return $this->url;
118
    }
119
}
120