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

Route::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Win\Mvc;
4
5
use Win\Helper\Url;
6
use Win\DesignPattern\Singleton;
7
8
/**
9
 * Rota de URL
10
 * 
11
 * Envia a requisição para o controller correto.
12
 * Veja as rotas em config/routes.php
13
 */
14
class Route extends Singleton {
15
16
	/**
17
	 * Se for atribuido algum valor indica que é uma rota personalizada
18
	 * @var mixed[]
19
	 */
20
	protected static $customUrl = [null, null];
21
22
	/**
23
	 * Retorna a nova Url
24
	 * @return mixed[]
25
	 */
26
	public function getCustomUrl() {
27
		return static::$customUrl;
28
	}
29
30
	/**
31
	 * Retorna TRUE se a URL foi personalizada
32
	 * @return boolean
33
	 */
34
	public function hasCustomUrl() {
35
		return (!is_null(static::$customUrl[0]));
36
	}
37
38
	/**
39
	 * Inicia o processo de Url personalizada
40
	 * retornando TRUE se alguma rota foi encontrada
41
	 * @return boolean
42
	 */
43
	public function run() {
44
		static::$customUrl = static::createCustomUrl();
45
		return $this->hasCustomUrl();
46
	}
47
48
	/**
49
	 * Percorre todas as rotas e retorna a nova Url
50
	 * 
51
	 * @return string[] Nova Url [0 => controller, 1 => action]
52
	 */
53
	protected function createCustomUrl() {
54
		$routeList = (array) Application::app()->getConfig('route', []);
55
		$search = ['', '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9', '$10'];
56
		$matches = [];
57
		foreach ($routeList as $url => $route):
58
			$exists = preg_match('@' . Url::instance()->format($url) . '$@', Url::instance()->getUrl(), $matches) == 1;
59
			if ($exists):
60
				$route = str_replace($search, $matches, $route) . '/';
61
				return explode('/', $route);
62
			endif;
63
		endforeach;
64
		return [null, null];
65
	}
66
67
	/**
68
	 * Cria um controller de acordo com a nova Url
69
	 *
70
	 * @return Controller|DefaultController
71
	 */
72
	public function createController() {
73
		return ControllerFactory::create(static::$customUrl[0], static::$customUrl[1]);
74
	}
75
76
}
77