-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.php
75 lines (62 loc) · 2.05 KB
/
Router.php
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
<?php
class Router
{
const GET = 'GET';
const POST = 'POST';
private $routeCollection = [];
public function get(string $uri, Closure $closure)
{
$parsedUri = $this->parseUri($uri);
$this->addRoute(self::GET, $parsedUri['path'], $parsedUri['paramsNum'], $closure);
}
public function post(string $uri, Closure $closure)
{
$parsedUri = $this->parseUri($uri);
$this->addRoute(self::POST, $parsedUri['path'], $parsedUri['paramsNum'], $closure);
}
public function run()
{
$route = $this->findRoute(
$this->routeCollection[$_SERVER['REQUEST_METHOD']],
explode('/', $_SERVER['REQUEST_URI'])
);
call_user_func_array($route['callback'], $route['params']);
}
private function addRoute(string $method, string $uri, int $paramsNum, Closure $closure)
{
$this->routeCollection[$method][$uri] = [
'paramsNum' => $paramsNum,
'callback' => $closure,
];
}
private function parseUri(string $uri)
{
$parsedUri = explode('/:', $uri);
return [
'path' => $parsedUri[0],
'paramsNum' => count($parsedUri) - 1,
];
}
private function findRoute(array $routes, array $uri_array)
{
$currentRoute = '/';
$isRouteFound = false;
while (!empty($uri_array)) {
$uriPiece = array_shift($uri_array);
$currentRoute = $currentRoute === '/' ? "${currentRoute}{$uriPiece}" : "{$currentRoute}/{$uriPiece}";
$route = $routes[$currentRoute] ?? null;
if (isset($route) && $route['paramsNum'] === count($uri_array)) {
$isRouteFound = true;
$params = $uri_array;
break;
}
}
if (!$isRouteFound) {
throw new Exception('Ошибка 404 – Страница не найдена', 404);
}
return [
'callback' => $routes[$currentRoute]['callback'],
'params' => $params,
];
}
}