-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoutes.php
More file actions
70 lines (61 loc) · 2.11 KB
/
Routes.php
File metadata and controls
70 lines (61 loc) · 2.11 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
<?php
namespace TypechoPlugin\ZaoApi;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
final class Routes
{
/** API 版本前缀(切 v2 只改这里) */
public const PREFIX = '/api/v1';
/** 路由名统一前缀,避免与其他插件冲突 */
public const NAME_PREFIX = 'zaoapi_';
/** 注册指定控制器类上使用了 #[Route] 的全部方法 */
public static function registerByAttributes(array $controllers): void
{
var_dump('注册指定控制器类上使用了 #[Route] 的全部方法');
foreach ($controllers as $controller) self::registerController($controller);
}
/** 注销指定控制器类上使用了 #[Route] 的全部方法 */
public static function unregisterByAttributes(array $controllers): void
{
foreach ($controllers as $controller) self::unregisterController($controller);
}
private static function registerController(string $controller): void
{
$ref = new \ReflectionClass($controller);
foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $m) {
foreach ($m->getAttributes(Route::class) as $attr) {
/** @var Route $meta */
$meta = $attr->newInstance();
$alias = self::NAME_PREFIX . $meta->name;
$path = self::join(self::PREFIX, $meta->path);
try {
\Utils\Helper::removeRoute($alias);
} catch (\Throwable $e) {
}
\Utils\Helper::addRoute($alias, $path, $controller, $m->getName());
}
}
}
private static function unregisterController(string $controller): void
{
$ref = new \ReflectionClass($controller);
foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $m) {
foreach ($m->getAttributes(Route::class) as $attr) {
$meta = $attr->newInstance();
$alias = self::NAME_PREFIX . $meta->name;
try {
\Utils\Helper::removeRoute($alias);
} catch (\Throwable $e) {
}
}
}
}
private static function join(string $prefix, string $path): string
{
$prefix = '/' . ltrim($prefix, '/');
$path = '/' . ltrim($path, '/');
return rtrim($prefix, '/') . $path;
}
}
// vim: set ts=2 sw=2 et: