Completed
Push — master ( baf9c0...cf2f5b )
by Wanderson
02:20
created

Url::setUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Win\Helper;
4
5
use Win\Request\Input;
6
use Win\DesignPattern\Singleton;
7
8
/**
9
 * Gerenciador de URL
10
 * 
11
 * Auxilia no gerenciamento de URLs
12
 */
13
class Url extends 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
	 * Adicionando base e sufixo se necessário
31
	 * @param string $url URL sem barra no final
32
	 * @return string
33
	 */
34
	public function format($url) {
35
		$url = rtrim($url, $this->sufix) . $this->sufix;
36
		return $url;
37
	}
38
39
	/**
40
	 * Redireciona para a url escolhida
41
	 * @param string $url
42
	 */
43
	public function redirect($url = '') {
44
		header('location:' . $this->getBaseUrl() . $this->format($url));
45
	}
46
47
	/**
48
	 * Retorna a URL base
49
	 * @return string
50
	 */
51
	public function getBaseUrl() {
52
		if (is_null($this->base)):
53
			$protocol = $this->getProtocol();
54
			$host = Input::server('HTTP_HOST');
55
			$script = Input::server('SCRIPT_NAME');
56
			$basePath = preg_replace('@/+$@', '', dirname($script)) . '/';
57
			$this->base = $protocol . '://' . $host . $basePath;
58
		endif;
59
		return $this->base;
60
	}
61
62
	/**
63
	 * Retorna o protocolo atual
64
	 * @return string (http|https)
65
	 */
66
	public function getProtocol() {
67
		if (is_null($this->protocol)):
68
			$this->protocol = Input::protocol();
69
		endif;
70
		return $this->protocol;
71
	}
72
73
	/**
74
	 * Retorna a URL atual
75
	 * @return string
76
	 */
77
	public function getUrl() {
78
		if (is_null($this->url)):
79
			$host = Input::server('HTTP_HOST');
80
			$url = '';
81
			if ($host):
82
				$requestUri = Input::server('REQUEST_URI');
83
				$context = explode($host, $this->getBaseUrl());
84
				$uri = (explode(end($context), $requestUri, 2));
85
				$url = end($uri);
86
			endif;
87
			$this->url = $this->format($url);
88
		endif;
89
		return $this->url;
90
	}
91
92
	/**
93
	 * Usada apenas para testes
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 getFragments() {
105
		$url = rtrim($this->getUrl(), $this->sufix);
106
		return explode('/', $url);
107
	}
108
109
}
110