-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
43 lines (40 loc) · 1.23 KB
/
Copy pathRouter.php
File metadata and controls
43 lines (40 loc) · 1.23 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
<?php
/**
* Microfy
* Router.php
* v0.1.3
* Author: SirCode
*/
class Router {
protected array $routes = [ 'GET'=>[], 'POST'=>[], 'PUT'=>[], 'DELETE'=>[] ];
public function get(string $path, callable $h): void {
$this->routes['GET'][$path] = $h;
}
public function post(string $path, callable $h): void {
$this->routes['POST'][$path] = $h;
}
public function dispatch(): void {
$method = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$path = ($base && strpos($requestUri, $base)===0)
? substr($requestUri, strlen($base))
: $requestUri;
$uri = rtrim($path, '/') ?: '/';
$routes = $this->routes[$method] ?? [];
if (isset($routes[$uri])) {
echo ($routes[$uri])();
return;
}
foreach ($routes as $route => $h) {
$pattern = '#^'.preg_replace('#\{[^}]+\}#','([^/]+)', $route).'$#';
if (preg_match($pattern, $uri, $m)) {
array_shift($m);
echo call_user_func_array($h, $m);
return;
}
}
http_response_code(404);
echo '404 Not Found';
}
}