Completed
Push — master ( e32bea...07ff99 )
by Wanderson
02:49
created

Application::redirect()   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
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Win\Mvc;
4
5
use Win\Helper\Url;
6
use Win\Request\Input;
7
use Win\Authentication\User;
8
9
/**
10
 * Application (WinPHP Framework)
11
 *
12
 * Framework em PHP baseado em MVC
13
 * Esta classe é responśavel por incluir as páginas de acordo com a URL e gerenciar a estrutura MVC
14
 * @author winPHP Framework <http://github.com/winframework/winphp/>
15
 * @version 0.1
16
 */
17
class Application {
18
19
	protected static $app = null;
20
21
	/** @var mixed[] */
22
	private $config;
23
	private $name;
24
	private $page;
25
	private $homePage = 'index';
26
	private $errorPageList = [
27
		404 => 'Página não encontrada',
28
		401 => 'Não autorizado',
29
		403 => 'Acesso negado',
30
		500 => 'Erro no Servidor',
31
		503 => 'Problemas de Conexão'
32
	];
33
	private $url;
34
	private $paramList;
35
	private $title;
36
37
	/** @var Controller Controller atual */
38
	public $controller;
39
40
	/** @var View View atual */
41
	public $view;
42
43
	/** @var User */
44
	private $user;
45
46
	/**
47
	 * Cria a aplicação principal
48
	 * @param mixed[] $config Configurações
49
	 */
50
	public function __construct($config = []) {
51
		static::$app = $this;
52
		$this->user = new User();
53
		$this->config = $config;
54
		$this->name = $this->getConfig('name', '');
55
56
		$this->setParamList(Url::instance()->getFragments());
57
		$this->controller = ControllerFactory::create($this->getParam(0), $this->getParam(1));
58
59
		if (Route::instance()->run()):
60
			$this->setParamList(Route::instance()->getCustomUrl());
61
			$this->controller = Route::instance()->createController();
62
		endif;
63
64
		$this->setPage($this->getParam(0));
65
		$this->view = ViewFactory::create($this->getParam(0), $this->paramList);
66
67
		$this->validatePage404();
68
	}
69
70
	/**
71
	 * Retorna um ponteiro para a aplicação principal
72
	 * @return static
73
	 */
74
	public static function app() {
75
		return static::$app;
76
	}
77
78
	/**
79
	 * Executa a applicação
80
	 * chamando o controller e criando o layout que contem a view
81
	 */
82
	public function run() {
83
		$this->controller->load();
84
		$layout = new Layout($this->controller->layout);
85
		$layout->load();
86
	}
87
88
	/**
89
	 * Retorna o usuário atual
90
	 * @return User
91
	 */
92
	public function getUser() {
93
		return $this->user;
94
	}
95
96
	/**
97
	 * Retorna uma configuração
98
	 * @param string $key Nome da configuração
99
	 * @param string $default Valor default, caso esta configuração esteja em branco
100
	 */
101
	public function getConfig($key, $default = '') {
102
		return (key_exists($key, $this->config)) ? $this->config[$key] : $default;
103
	}
104
105
	/** @return string */
106
	public function getName() {
107
		return $this->name;
108
	}
109
110
	/** @return string */
111
	public function getFullUrl() {
112
		return $this->getBaseUrl() . $this->getUrl();
113
	}
114
115
	/** @return string */
116
	public function getBaseUrl() {
117
		return Url::instance()->getBaseUrl();
118
	}
119
120
	/**
121
	 * Retorna a URL Atual
122
	 * @return string
123
	 */
124
	public function getUrl() {
125
		if (is_null($this->url)):
126
			$this->url = Url::instance()->format(implode('/', $this->getParamList()));
127
		endif;
128
		return $this->url;
129
	}
130
131
	/** @return string */
132
	public function getServerName() {
133
		return Input::server('SERVER_NAME', FILTER_SANITIZE_STRING);
134
	}
135
136
	/** @return bolean */
137
	public function isLocalHost() {
138
		$localAddress = ['localhost', '127.0.0.1', '::1', null];
139
		return (in_array($this->getServerName(), $localAddress) || strpos($this->getServerName(), '192.168') !== false);
140
	}
141
142
	/**
143
	 * Retorna o nome da página atual
144
	 * @return string
145
	 */
146
	public function getPage() {
147
		return $this->page;
148
	}
149
150
	/** @param string $page */
151
	protected function setPage($page) {
152
		$this->page = $page;
153
	}
154
155
	/**
156
	 * Retorna o nome da página inicial
157
	 * @return string
158
	 */
159
	public function getHomePage() {
160
		return $this->homePage;
161
	}
162
163
	/**
164
	 * Retorna TRUE se está na página inicial
165
	 * @return boolean
166
	 */
167
	public function isHomePage() {
168
		return (boolean) ($this->page === $this->homePage);
169
	}
170
171
	/**
172
	 * Retorna TRUE se está em alguma página de erro (404, 403, 503, etc)
173
	 * @return boolean
174
	 */
175
	public function isErrorPage() {
176
		return (boolean) (key_exists((int) $this->page, $this->errorPageList));
177
	}
178
179
	/**
180
	 * Retorna um array com todos os parametros da URL
181
	 * @return string[]
182
	 */
183
	protected function getParamList() {
184
		return $this->paramList;
185
	}
186
187
	/**
188
	 * Define os parâmetros.
189
	 * Se estiver vazio, utiliza os parâmetros padrão.
190
	 * @param string[] $paramList
191
	 */
192
	private function setParamList($paramList) {
193
		$paramDefaulf = [$this->homePage, 'index'];
194
		$this->paramList = array_replace($paramDefaulf, array_filter($paramList));
195
	}
196
197
	/**
198
	 * Retorna uma parte da URL
199
	 * @param int $position Parte escolhida
200
	 * @return string
201
	 */
202
	public function getParam($position) {
203
		return (key_exists($position, $this->paramList)) ? $this->paramList[$position] : '';
204
	}
205
206
	/**
207
	 * Retorna o titulo da página atual
208
	 * @return string
209
	 */
210
	public function getTitle() {
211
		if (is_null($this->title)):
212
			$this->title = ucwords(str_replace('-', ' ', $this->page));
213
		endif;
214
		return $this->title;
215
	}
216
217
	/**
218
	 * Define o titulo da página
219
	 * @param string $title
220
	 */
221
	public function setTitle($title) {
222
		$this->title = $title;
223
	}
224
225
	/**
226
	 * Redireciona para a URL
227
	 * @param string $url
228
	 */
229
	public function redirect($url = '') {
230
		Url::instance()->redirect($url);
231
	}
232
233
	/**
234
	 * Chama pageNotFound se o usuario acessar /404
235
	 *
236
	 * Isso garante que todas as funcionalidades de pageNotFound serão executadas
237
	 * mesmo se a página existente 404 for acessada
238
	 */
239
	private function validatePage404() {
240
		if ($this->getParam(0) === '404'):
241
			$this->pageNotFound();
242
		endif;
243
	}
244
245
	/** Define a página como 404 */
246
	public function pageNotFound() {
247
		$this->errorPage(404);
248
	}
249
250
	/**
251
	 * Define a página como "$errorCode"
252
	 * @param int $errorCode [401, 404, 500, etc]
253
	 */
254
	public function errorPage($errorCode) {
255
		if (key_exists($errorCode, $this->errorPageList)):
256
			$this->page = (string) $errorCode;
257
			$this->view = new View($errorCode);
258
			$this->title = $this->errorPageList[$errorCode];
259
			$this->controller = ControllerFactory::create('Error' . $errorCode);
260
			http_response_code($errorCode);
261
			if ($this->getParam(0) !== (string) $errorCode):
262
				$this->controller->load();
263
			endif;
264
		endif;
265
	}
266
267
}
268