-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRouter.php
More file actions
112 lines (99 loc) · 2.8 KB
/
Copy pathRouter.php
File metadata and controls
112 lines (99 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* @Author: ohmyga
* @Date: 2021-10-22 12:04:31
* @LastEditTime: 2021-10-30 17:30:27
*/
namespace OAPI\HTTP;
use OAPI\Framework;
use OAPI\HTTP\Router\Parser;
use OAPI\Console\Console;
use function count;
use function is_array;
class Router
{
/**
* 路由表
*/
private static $_routes = [];
/**
* 初始化
*/
public function __construct()
{
}
/**
* 路由分发函数
*/
public static function dispatch()
{
$request = Framework::$server_method["request"];
$response = Framework::$server_method["response"];
if (strtolower($request->server["request_method"]) == "options") {
HTTP::handleOptions();
$response->end();
return true;
}
$_has = false;
$request->server["request_uri"] = str_replace("//", "/", $request->server["request_uri"]);
foreach (self::$_routes as $route) {
if (preg_match($route['regx'], $request->server["request_uri"], $matches)) {
call_user_func($route["widget"], $request, $response, $matches);
$_has = true;
Console::success("[{$request->server["request_uri"]}]在路由表中匹配成功", "Router");
}
}
if ($_has === false) {
HTTP::sendJSON(false, 404, "404 Not Found");
Console::warning("[{$request->server["request_uri"]}]在路由表中匹配失败 (404)", "Router");
}
}
/**
* 添加路由
*
* @param array $route 单个路由
* @return array 路由解析结果
*/
public static function add(array $route): array
{
$route["disableVersion"] = (isset($route["disableVersion"])) ? $route["disableVersion"] : false;
if ($route["url"] != "/" && $route["disableVersion"] != "true") {
$route["version"] = (!empty($route["version"])) ? $route["version"] : "1";
}
$parser = new Parser([$route]);
self::$_routes[] = $parser->parse()[0];
return $parser->parse()[0];
}
/**
* 删除路由
*
* @param int $id 路由表中的 ID
* @return array 路由表内容
*/
public static function remove($id): array
{
if (!empty(self::$_routes[$id])) {
unset(self::$_routes[$id]);
}
return self::$_routes;
}
/**
* 路由重新排序
*
* @return array
*/
public static function values(): array
{
self::$_routes = array_values(self::$_routes);
return self::$_routes;
}
/**
* 获取已解析的路由表
*
* @return array
*/
public static function getRoutes(): array
{
return (is_array(self::$_routes) && count(self::$_routes) > 0) ? self::$_routes : [];
}
}