-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAttributeRouteRegistrar.php
More file actions
106 lines (87 loc) · 2.99 KB
/
AttributeRouteRegistrar.php
File metadata and controls
106 lines (87 loc) · 2.99 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
<?php
declare(strict_types=1);
namespace Bow\Router;
use Bow\Router\Attributes\Controller;
use Bow\Router\Attributes\Route as RouteAttribute;
use ReflectionClass;
use ReflectionMethod;
class AttributeRouteRegistrar
{
/**
* The router instance
*
* @var Router
*/
private Router $router;
/**
* @param Router $router
*/
public function __construct(Router $router)
{
$this->router = $router;
}
/**
* Register routes from controller classes
*
* @param string|array $controllers
* @return void
*/
public function register(string|array $controllers): void
{
$controllers = is_array($controllers) ? $controllers : [$controllers];
foreach ($controllers as $controller) {
$this->registerController($controller);
}
}
/**
* Register routes from controller
*
* @param string $controllerClass
* @return void
*/
private function registerController(string $controllerClass): void
{
$reflection = new ReflectionClass($controllerClass);
// Get controller attribute
$controllerAttributes = $reflection->getAttributes(Controller::class);
$controllerAttribute = !empty($controllerAttributes) ? $controllerAttributes[0]->newInstance() : null;
$prefix = $controllerAttribute?->getPrefix() ?? '';
$controllerMiddleware = $controllerAttribute?->getMiddleware() ?? [];
// Scan methods
foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (str_starts_with($method->getName(), '__')) {
continue;
}
// Get route attributes
$routeAttributes = $method->getAttributes(
RouteAttribute::class,
\ReflectionAttribute::IS_INSTANCEOF
);
foreach ($routeAttributes as $attribute) {
/** @var RouteAttribute $routeAttr */
$routeAttr = $attribute->newInstance();
// Build path
$routePath = $routeAttr->getPath();
$routePath = '/' . ltrim($routePath, '/');
$fullPath = $prefix !== '' ? rtrim($prefix, '/') . $routePath : $routePath;
// Merge middleware
$middleware = array_merge($controllerMiddleware, $routeAttr->getMiddleware());
// Register route
$route = $this->router->match(
$routeAttr->getMethods(),
$fullPath,
[$controllerClass, $method->getName()]
);
if (!empty($middleware)) {
$route->middleware($middleware);
}
if (!empty($routeAttr->getWhere())) {
$route->where($routeAttr->getWhere());
}
if ($routeAttr->getName() !== null) {
$route->name($routeAttr->getName());
}
}
}
}
}