Passed
Branch v1.5.1 (9f4477)
by Wanderson
01:49
created

Router::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Win\Request;
4
5
use Win\HttpException;
6
7
/**
8
 * Rota de URL
9
 *
10
 * Define o Controller@action a ser executado baseado na URL
11
 * @see "config/routes.php"
12
 */
13
class Router
14
{
15
	/** @var string[] */
16
	protected static $routes = [];
17
18
	/**
19
	 * Adiciona as rotas
20
	 * @param string $namespace
21
	 * @param string[] $routes
22
	 */
23
	public static function add($namespace, $routes)
24
	{
25
		foreach ($routes as $request => $destination) {
26
			static::$routes[$request] = $namespace . $destination;
27
		}
28
	}
29
30
	/**
31
	 * Percorre todas as rotas e retorna o destino final
32
	 * @return array Destino
33
	 * @example return [Controller, action, [..$args]]
34
	 */
35
	public static function getDestination()
36
	{
37
		$url = Url::instance();
38
		$matches = [];
39
40
		foreach (static::$routes as $request => $destination) {
41
			$pattern = '@^' . $url->format($request) . '$@';
42
			$match = preg_match($pattern, $url->getUrl(), $matches);
43
			if ($match) {
44
				$destination = array_pad(explode('@', $destination), 2, '');
45
				$destination[] = (array) array_splice($matches, 1);
46
47
				return $destination;
48
			}
49
		}
50
51
		throw new HttpException('Route not found', 404);
52
	}
53
}
54