This repository was archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerResolver.php
More file actions
88 lines (67 loc) · 2.37 KB
/
ControllerResolver.php
File metadata and controls
88 lines (67 loc) · 2.37 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
<?php
namespace Pianissimo\Component\Framework;
use LogicException;
use Pianissimo\Component\DependencyInjection\ContainerInterface;
use Pianissimo\Component\Framework\Exception\NotFoundHttpException;
class ControllerResolver
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var Router
*/
private $router;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->router = $container->get(Router::class);
}
/**
* @throws NotFoundHttpException
*/
public function resolve(Request $request): Callable
{
$router = $this->router;
$path = $_SERVER['PATH_INFO'] ?? '';
$route = $router->matchRoute($path);
if ($route === null) {
throw new NotFoundHttpException('404 Not Found');
}
$class = $route->getClass();
$method = $route->getMethod();
$parameters = $this->resolveParameters($route->getPath(), $path);
$controller = $this->container->get($class);
return function () use ($controller, $method, $parameters) {
return $controller->$method(...$parameters);
};
}
/**
* Resolves the route parameters using the requested path.
*/
private function resolveParameters(string $routePath, string $requestPath): array
{
$routeParts = array_values(array_filter(explode('/', $routePath)));
$requestPathParts = array_values(array_filter(explode('/', $requestPath)));
$parameters = [];
$count = -1;
foreach ($routeParts as $routePart) {
$count++;
if (array_key_exists($count, $requestPathParts) === false) {
throw new LogicException('Can not resolve route parameter, route does not match with the requested URL');
}
if ($routePart === $requestPathParts[$count]) {
continue;
}
$firstCharacter = substr($routePart, 0, 1);
$lastCharacter = substr($routePart, -1);
if ($firstCharacter === '{' && $lastCharacter === '}') {
$parameters[] = $requestPathParts[$count];
continue;
}
throw new LogicException('Can not resolve route parameter, route does not match with the requested URL');
}
return $parameters;
}
}