Passed
Branch scrutinizer (dafd44)
by Wanderson
01:40
created

Url::getBaseUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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