Passed
Branch tests1.5 (e599bd)
by Wanderson
01:46
created

Url::setUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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