Passed
Branch tests1.5 (af713c)
by Wanderson
01:19
created

Url::getFragments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Win\Request;
4
5
use Win\DesignPattern\SingletonTrait;
6
7
/**
8
 * Gerenciador de URL
9
 * 
10
 */
11
class Url {
12
13
	use SingletonTrait;
14
15
	protected $base = null;
16
	protected $url = null;
17
	protected $sufix = '/';
18
	protected $protocol = null;
19
20
	/**
21
	 * Define um novo sufixo de URL
22
	 * @param string $sufix
23
	 */
24
	public function setSufix($sufix) {
25
		$this->sufix = $sufix;
26
	}
27
28
	/**
29
	 * Retorna no formato de URL
30
	 * @param string $url
31
	 * @return string
32
	 */
33
	public function format($url) {
34
		return rtrim($url, $this->sufix) . $this->sufix;
35
	}
36
37
	/**
38
	 * Redireciona para a URL escolhida
39
	 * @param string $url URL relativa ou absoluta
40
	 */
41
	public function redirect($url = '') {
42
		if (strpos($url, '://') === false) {
43
			$url = $this->getBaseUrl() . $url;
44
		}
45
		Header::instance()->set('location', $url);
46
	}
47
48
	/**
49
	 * Retorna a URL base
50
	 * @return string
51
	 */
52
	public function getBaseUrl() {
53
		if (is_null($this->base)):
54
			$protocol = $this->getProtocol();
55
			$host = Input::server('HTTP_HOST');
56
			$script = Input::server('SCRIPT_NAME');
57
			$basePath = preg_replace('@/+$@', '', dirname($script)) . '/';
58
			$this->base = $protocol . '://' . $host . $basePath;
59
		endif;
60
		return $this->base;
61
	}
62
63
	/**
64
	 * Retorna o protocolo atual
65
	 * @return string (http|https)
66
	 */
67
	public function getProtocol() {
68
		if (is_null($this->protocol)):
69
			$this->protocol = Input::protocol();
70
		endif;
71
		return $this->protocol;
72
	}
73
74
	/**
75
	 * Retorna a URL atual
76
	 * @return string
77
	 */
78
	public function getUrl() {
79
		if (is_null($this->url)):
80
			$host = Input::server('HTTP_HOST');
81
			$url = '';
82
			if ($host):
83
				$requestUri = explode('?', Input::server('REQUEST_URI'));
84
				$context = explode($host, $this->getBaseUrl());
85
				$uri = (explode(end($context), $requestUri[0], 2));
86
				$url = end($uri);
87
			endif;
88
			$this->url = $this->format($url);
89
		endif;
90
		return $this->url;
91
	}
92
93
	/**
94
	 * @param string $url
95
	 */
96
	public function setUrl($url) {
97
		$this->url = $this->format($url . '/');
98
	}
99
100
	/**
101
	 * Retorna o array de fragmentos da URL
102
	 * @return string[]
103
	 */
104
	public function getSegments() {
105
		$url = rtrim($this->getUrl(), $this->sufix);
106
		return explode('/', $url);
107
	}
108
109
}
110