-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.php
More file actions
97 lines (69 loc) · 2.1 KB
/
router.php
File metadata and controls
97 lines (69 loc) · 2.1 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
<?php
declare ( strict_types =1 );
//namespace App;
class Router{
private $handlers = [];
private $notFoundHandler;
private const METHOD_POST = 'POST';
private const METHOD_GET = 'GET';
private const METHOD_PUT = 'PUT';
public function get(string $path, $handler) : void
{
$this->addHandler(self::METHOD_GET, $path, $handler);
}
public function post(string $path, $handler) : void
{
$this->addHandler(self::METHOD_POST, $path, $handler);
}
public function put(string $path, $handler) : void
{
$this->addHandler(self::METHOD_PUT, $path, $handler);
}
public function addNotFoundHandler($handler) :void
{
$this->addNotFoundHandler = $handler;
}
private function addHandler(string $method, string $path, $handler) : void
{
$this->handlers[$method . $path] =
[
'path' => $path,
'method' => $method,
'handler' => $handler
];
}
public function run()
{
// find and execute handler for route
$requestUri = parse_url($_SERVER['REQUEST_URI']);
$requestPath = $requestUri['path'];
$method = $_SERVER['REQUEST_METHOD']; // 'POST', 'GET', etc.
$callback = null;
foreach($this->handlers as $handler)
{
if($handler['path'] === $requestPath && // '/about', for example
$method === $handler['method']) // GET, for example
{
$callback = $handler['handler']; // method associated with path & method
}
}
if(!$callback)
{
header("HTTP/1.1 404 Not Found", true, 404);
if(!empty($this->addNotFoundHandler)) // found custom 404 handler
{
$callback = $this->addNotFoundHandler;
}
else
{
return;
}
}
call_user_func_array($callback,
[
array_merge($_GET, $_POST) // ??
]
);
}
}
?>