|
1
|
|
|
<?php |
|
2
|
|
|
namespace WebServCo\Framework\Libraries; |
|
3
|
|
|
|
|
4
|
|
|
final class Router extends \WebServCo\Framework\AbstractLibrary |
|
5
|
|
|
{ |
|
6
|
|
|
public function getRoute($requestCustom, $routes, $extraArgs = []) |
|
7
|
|
|
{ |
|
8
|
|
|
$routeString = $this->parseCustomRoutes($requestCustom, $routes); |
|
9
|
|
|
if (empty($routeString) || 'index' == $routeString) { |
|
10
|
|
|
$defaultRoute = $this->setting('default_route'); |
|
11
|
|
|
if (!isset($defaultRoute[1])) { |
|
12
|
|
|
throw new \ErrorException("Default route missing or not valid"); |
|
13
|
|
|
} |
|
14
|
|
|
return $defaultRoute; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
$controller = ''; |
|
18
|
|
|
$action = ''; |
|
19
|
|
|
$args = []; |
|
20
|
|
|
|
|
21
|
|
|
$parts = explode('/', $routeString, 3); |
|
22
|
|
|
if (!empty($parts['0'])) { |
|
23
|
|
|
$controller = $parts[0]; |
|
24
|
|
|
} |
|
25
|
|
|
if (!empty($parts['1'])) { |
|
26
|
|
|
$action = $parts[1]; |
|
27
|
|
|
} |
|
28
|
|
|
if (!empty($parts['2'])) { |
|
29
|
|
|
$args = explode('/', $parts[2]); |
|
30
|
|
|
} |
|
31
|
|
|
if (!empty($extraArgs)) { |
|
32
|
|
|
foreach ($extraArgs as $k => $v) { |
|
33
|
|
|
$args[] = $v; |
|
34
|
|
|
} |
|
35
|
|
|
} |
|
36
|
|
|
return [$controller, $action, $args]; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
private function parseCustomRoutes($requestCustom, $routes) |
|
40
|
|
|
{ |
|
41
|
|
|
if (is_array($routes)) { |
|
42
|
|
|
foreach ($routes as $k => $v) { |
|
43
|
|
|
$k = str_replace(['{num}','{any}'], ['[0-9]+','.+'], $k); |
|
44
|
|
|
/** |
|
45
|
|
|
* Check for a custom route match. |
|
46
|
|
|
*/ |
|
47
|
|
|
if (preg_match("#^{$k}$#", $requestCustom) || |
|
48
|
|
|
preg_match("#^{$k}/$#", $requestCustom) |
|
49
|
|
|
) { |
|
50
|
|
|
/** |
|
51
|
|
|
* Check for back references. |
|
52
|
|
|
*/ |
|
53
|
|
|
if (false !== strpos($v, '$') && false !== strpos($k, '(')) { |
|
54
|
|
|
/** |
|
55
|
|
|
* Parse request. |
|
56
|
|
|
*/ |
|
57
|
|
|
$v = preg_replace("#^{$k}$#", $v, $requestCustom); |
|
58
|
|
|
} |
|
59
|
|
|
return $v; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
return $requestCustom; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|