Completed
Push — master ( a9fbcc...a7b0c2 )
by Wanderson
02:19
created

Application::errorPage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
nc 3
nop 1
dl 0
loc 13
rs 9.4285
c 1
b 0
f 0
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 1.0
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 = null;
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->config = $config;
53
		$this->name = $this->getConfig('name', '');
54
55
		$this->setParamList(Url::instance()->getFragments());
56
		$this->controller = ControllerFactory::create($this->getParam(0), $this->getParam(1));
57
58
		if (Route::instance()->run()):
59
			$this->setParamList(Route::instance()->getCustomUrl());
60
			$this->controller = Route::instance()->createController();
61
		endif;
62
63
		$this->setPage($this->getParam(0));
64
		$this->view = ViewFactory::create($this->getParam(0), $this->paramList);
65
66
		$this->validateErrorPage();
67
	}
68
69
	/**
70
	 * Retorna um ponteiro para a aplicação principal
71
	 * @return static
72
	 */
73
	public static function app() {
74
		return static::$app;
75
	}
76
77
	/**
78
	 * Executa a applicação
79
	 * chamando o controller e criando o layout que contem a view
80
	 */
81
	public function run() {
82
		$this->controller->load();
83
		$layout = new Layout($this->controller->layout);
84
		$layout->load();
85
	}
86
87
	/**
88
	 * Retorna o usuário atual
89
	 * @return User
90
	 */
91
	public function getUser() {
92
		if (is_null($this->user)):
93
			$this->user = User::getCurrentUser();
94
		endif;
95
		return $this->user;
96
	}
97
98
	/**
99
	 * Retorna uma configuração
100
	 * @param string $key Nome da configuração
101
	 * @param string $default Valor default, caso esta configuração esteja em branco
102
	 */
103
	public function getConfig($key, $default = '') {
104
		return (key_exists($key, $this->config)) ? $this->config[$key] : $default;
105
	}
106
107
	/** @return string */
108
	public function getName() {
109
		return $this->name;
110
	}
111
112
	/** @return string */
113
	public function getFullUrl() {
114
		return $this->getBaseUrl() . $this->getUrl();
115
	}
116
117
	/** @return string */
118
	public function getBaseUrl() {
119
		return Url::instance()->getBaseUrl();
120
	}
121
122
	/**
123
	 * Retorna a URL Atual
124
	 * @return string
125
	 */
126
	public function getUrl() {
127
		if (is_null($this->url)):
128
			$this->url = Url::instance()->format(implode('/', $this->getParamList()));
129
		endif;
130
		return $this->url;
131
	}
132
133
	/** @return string */
134
	public function getServerName() {
135
		return Input::server('SERVER_NAME', FILTER_SANITIZE_STRING);
136
	}
137
138
	/** @return bolean */
139
	public function isLocalHost() {
140
		$localAddress = ['localhost', '127.0.0.1', '::1', null];
141
		return (in_array($this->getServerName(), $localAddress) || strpos($this->getServerName(), '192.168') !== false);
142
	}
143
144
	/**
145
	 * Retorna o nome da página atual
146
	 * @return string
147
	 */
148
	public function getPage() {
149
		return $this->page;
150
	}
151
152
	/** @param string $page */
153
	protected function setPage($page) {
154
		$this->page = $page;
155
	}
156
157
	/**
158
	 * Retorna o nome da página inicial
159
	 * @return string
160
	 */
161
	public function getHomePage() {
162
		return $this->homePage;
163
	}
164
165
	/**
166
	 * Retorna TRUE se está na página inicial
167
	 * @return boolean
168
	 */
169
	public function isHomePage() {
170
		return (boolean) ($this->page === $this->homePage);
171
	}
172
173
	/**
174
	 * Retorna TRUE se está em alguma página de erro (404, 403, 503, etc)
175
	 * @return boolean
176
	 */
177
	public function isErrorPage() {
178
		return (boolean) (key_exists((int) $this->page, $this->errorPageList));
179
	}
180
181
	/**
182
	 * Retorna um array com todos os parametros da URL
183
	 * @return string[]
184
	 */
185
	protected function getParamList() {
186
		return $this->paramList;
187
	}
188
189
	/**
190
	 * Define os parâmetros.
191
	 * Se estiver vazio, utiliza os parâmetros padrão.
192
	 * @param string[] $paramList
193
	 */
194
	private function setParamList($paramList) {
195
		$paramDefaulf = [$this->homePage, 'index'];
196
		$this->paramList = array_replace($paramDefaulf, array_filter($paramList));
197
	}
198
199
	/**
200
	 * Retorna uma parte da URL
201
	 * @param int $position Parte escolhida
202
	 * @return string
203
	 */
204
	public function getParam($position) {
205
		return (key_exists($position, $this->paramList)) ? $this->paramList[$position] : '';
206
	}
207
208
	/**
209
	 * Retorna o titulo da página atual
210
	 * @return string
211
	 */
212
	public function getTitle() {
213
		if (is_null($this->title)):
214
			$this->title = ucwords(str_replace('-', ' ', $this->page));
215
		endif;
216
		return $this->title;
217
	}
218
219
	/**
220
	 * Define o titulo da página
221
	 * @param string $title
222
	 */
223
	public function setTitle($title) {
224
		$this->title = $title;
225
	}
226
227
	/**
228
	 * Redireciona para a URL
229
	 * @param string $url
230
	 */
231
	public function redirect($url = '') {
232
		Url::instance()->redirect($url);
233
	}
234
235
	/**
236
	 * Atualiza a mesma página
237
	 * @param string $url
0 ignored issues
show
Bug introduced by
There is no parameter named $url. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
238
	 */
239
	public function refresh() {
240
		Url::instance()->redirect($this->getUrl());
241
	}
242
243
	/**
244
	 * Chama pageNotFound se o usuario acessar /404
245
	 *
246
	 * Isso garante que todas as funcionalidades de pageNotFound serão executadas
247
	 * mesmo se a página existente 404 for acessada
248
	 */
249
	private function validateErrorPage() {
250
		if (key_exists((int) $this->getParam(0), $this->errorPageList)):
251
			$this->errorPage((int) $this->getParam(0));
252
		endif;
253
	}
254
255
	/** Define a página como 404 */
256
	public function pageNotFound() {
257
		$this->errorPage(404);
258
	}
259
260
	/**
261
	 * Define a página como "$errorCode"
262
	 * @param int $errorCode [401, 404, 500, etc]
263
	 */
264
	public function errorPage($errorCode) {
265
		if (key_exists($errorCode, $this->errorPageList)):
266
			$this->stopControllerIf403($errorCode);
267
			$this->page = (string) $errorCode;
268
			$this->view = new View($errorCode);
269
			$this->title = $this->errorPageList[$errorCode];
270
			$this->controller = ControllerFactory::create('Error' . $errorCode);
271
			http_response_code($errorCode);
272
			if ($this->getParam(0) !== (string) $errorCode):
273
				$this->controller->reload();
274
			endif;
275
		endif;
276
	}
277
278
	/**
279
	 * Trava o carregamento do controller, se ele definir um erro 403
280
	 * Isso evita que códigos sem permissões de acesso nunca sejam executados
281
	 * @param int $errorCode
282
	 */
283
	private function stopControllerIf403($errorCode) {
284
		if ($errorCode == 403 && $this->getParam(0) !== (string) $errorCode):
285
			$this->redirect(403 . '/index/' . $this->getUrl());
286
		endif;
287
	}
288
289
}
290