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 \WebServCo\Framework\Exceptions\ApplicationException( |
13
|
|
|
"Default route missing or not valid" |
14
|
|
|
); |
15
|
|
|
} |
16
|
|
|
return $defaultRoute; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
$parts = explode('/', $routeString, 3); |
20
|
|
|
|
21
|
|
|
if (empty($parts[1])) { |
22
|
|
|
throw new \WebServCo\Framework\Exceptions\NotFoundException( |
23
|
|
|
sprintf('The requested resource "%s" was not found', $routeString) |
24
|
|
|
); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$controller = $parts[0]; |
28
|
|
|
$action = $parts[1]; |
29
|
|
|
$args = []; |
30
|
|
|
|
31
|
|
|
if (!empty($parts['2'])) { |
32
|
|
|
$args = explode('/', $parts[2]); |
33
|
|
|
} |
34
|
|
|
if (!empty($extraArgs)) { |
35
|
|
|
foreach ($extraArgs as $k => $v) { |
36
|
|
|
$args[] = $v; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
return [$controller, $action, $args]; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function parseCustomRoutes($requestCustom, $routes) |
43
|
|
|
{ |
44
|
|
|
if (is_array($routes)) { |
45
|
|
|
foreach ($routes as $k => $v) { |
46
|
|
|
$k = str_replace(['{num}','{any}'], ['[0-9]+','.+'], $k); |
47
|
|
|
/** |
48
|
|
|
* Check for a custom route match. |
49
|
|
|
*/ |
50
|
|
|
if (preg_match("#^{$k}$#", $requestCustom) || |
51
|
|
|
preg_match("#^{$k}/$#", $requestCustom) |
52
|
|
|
) { |
53
|
|
|
/** |
54
|
|
|
* Check for back references. |
55
|
|
|
*/ |
56
|
|
|
if (false !== strpos($v, '$') && false !== strpos($k, '(')) { |
57
|
|
|
/** |
58
|
|
|
* Parse request. |
59
|
|
|
*/ |
60
|
|
|
$v = preg_replace("#^{$k}$#", $v, $requestCustom); |
61
|
|
|
} |
62
|
|
|
return $v; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
return $requestCustom; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|