-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.php
61 lines (50 loc) · 1.57 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
<?php
namespace Logeecom\Router;
use Exception;
/**
* Router class. Specifies which controller calls which function for the received request.
*/
class Router
{
/**
* Array of routes.
*
* @var RouteMapping[]
*/
private array $routeMappings;
/**
* @throws Exception
*/
public function __construct(string $routeMappingConfigPath)
{
$mappings = include $routeMappingConfigPath;
foreach ($mappings as $mapping) {
$this->routeMappings[] = new RouteMapping(
$mapping[RouteMappingKey::REQUEST_HTTP_METHOD],
$mapping[RouteMappingKey::REQUEST_PATH],
$mapping[RouteMappingKey::CONTROLLER_CLASS_NAME],
$mapping[RouteMappingKey::CONTROLLER_METHOD_NAME],
$mapping[RouteMappingKey::MIDDLEWARE_CLASS_NAMES],
);
}
}
/**
* Resolves appropriate route mapping for the received request.
*
* @param RequestInterface $request - Received client HTTP request.
* @return RouteMapping|null
* @throws Exception
*/
public function resolveRouteMapping(RequestInterface $request): ?RouteMapping
{
$requestMethod = $request->getMethod();
$requestPath = $request->getPath();
foreach ($this->routeMappings as $routeMapping) {
if ($routeMapping->matches($requestMethod, $requestPath)) {
$request->setPathParameters($routeMapping->parsePathParameters($requestPath));
return $routeMapping;
}
}
return null;
}
}