-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
70 lines (60 loc) · 1.78 KB
/
Router.php
File metadata and controls
70 lines (60 loc) · 1.78 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Core;
use \ReflectionMethod;
use \ReflectionClass;
use Core\RequestMethods\RequestMethod;
/**
* Handles module routes
*
* @author azcraft
*/
class Router
{
private RouterNode $node;
public function __construct()
{
$this->node = new RouterNode();
}
/**
* Loads module into this route table.
* @param string $moduleName
* @throws Exception
*/
public function add(string $moduleName, string $uri = "/")
{
$module = new ReflectionClass($moduleName);
$methods = $module->getMethods();
foreach ($methods as $method){
$attributes = $method->getAttributes();
if (!$method->isStatic()){
throw new Exception("Module $moduleName can have only static members");
}
foreach ($attributes as $attribute){
$instance = $attribute->newInstance();
$instance->setTarget($method);
if ($instance instanceof RequestMethod){
$methodURI = $uri . $instance->path();
$this->node->addByUri($instance, $methodURI);
}
}
}
}
/**
* Calls module startups and the requested method or the closest fallback method.
* @param Request $req
* @return RequestResponse
*/
public function process(Request $req): RequestResponse
{
$response = $this->node->run($req);
if (!isset($response)){
throw new Exception("Could not handle request. No matching method or fallback found.");
}
return $response;
}
}