Completed
Push — master ( c7b167...faaa80 )
by Wanderson
02:08
created

Application::validateErrorPage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 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 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 = 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
	 * Chama pageNotFound se o usuario acessar /404
237
	 *
238
	 * Isso garante que todas as funcionalidades de pageNotFound serão executadas
239
	 * mesmo se a página existente 404 for acessada
240
	 */
241
	private function validateErrorPage() {
242
		if (key_exists((int) $this->getParam(0), $this->errorPageList)):
243
			$this->errorPage((int) $this->getParam(0));
244
		endif;
245
	}
246
247
	/** Define a página como 404 */
248
	public function pageNotFound() {
249
		$this->errorPage(404);
250
	}
251
252
	/**
253
	 * Define a página como "$errorCode"
254
	 * @param int $errorCode [401, 404, 500, etc]
255
	 */
256
	public function errorPage($errorCode) {
257
		if (key_exists($errorCode, $this->errorPageList)):
258
			if ($errorCode == 403 && $this->getParam(0) !== (string) $errorCode):
259
				$this->redirect(403);
260
			endif;
261
262
			$this->page = (string) $errorCode;
263
			$this->view = new View($errorCode);
264
			$this->title = $this->errorPageList[$errorCode];
265
			$this->controller = ControllerFactory::create('Error' . $errorCode);
266
			http_response_code($errorCode);
267
			if ($this->getParam(0) !== (string) $errorCode):
268
				$this->controller->reload();
269
			endif;
270
		endif;
271
	}
272
273
}
274