1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Stitcher\Application; |
4
|
|
|
|
5
|
|
|
use FastRoute\Dispatcher; |
6
|
|
|
use FastRoute\Dispatcher\GroupCountBased; |
7
|
|
|
use FastRoute\RouteCollector; |
8
|
|
|
use GuzzleHttp\Psr7\Request; |
9
|
|
|
use GuzzleHttp\Psr7\Response; |
10
|
|
|
use Stitcher\App; |
11
|
|
|
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; |
12
|
|
|
|
13
|
|
|
class Router |
14
|
|
|
{ |
15
|
|
|
protected $routeCollector; |
16
|
|
|
|
17
|
4 |
|
public function __construct(RouteCollector $routeCollector) |
18
|
|
|
{ |
19
|
4 |
|
$this->routeCollector = $routeCollector; |
20
|
4 |
|
} |
21
|
|
|
|
22
|
2 |
|
public function get(string $url, string $controller): Router |
23
|
|
|
{ |
24
|
2 |
|
$this->routeCollector->addRoute('GET', $url, [$controller, 'handle']); |
25
|
|
|
|
26
|
2 |
|
return $this; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function post(string $url, string $controller): Router |
30
|
|
|
{ |
31
|
|
|
$this->routeCollector->addRoute('POST', $url, [$controller, 'handle']); |
32
|
|
|
|
33
|
|
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
1 |
|
public function dispatch(Request $request): ?Response |
37
|
|
|
{ |
38
|
1 |
|
$dispatcher = new GroupCountBased($this->routeCollector->getData()); |
39
|
|
|
|
40
|
1 |
|
$routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath()); |
41
|
|
|
|
42
|
1 |
|
if ($routeInfo[0] !== Dispatcher::FOUND) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
$handler = $this->resolveHandler($routeInfo[1]); |
47
|
1 |
|
$parameters = $routeInfo[2]; |
48
|
|
|
|
49
|
1 |
|
return call_user_func_array( |
50
|
1 |
|
$handler, |
51
|
1 |
|
array_merge($parameters, [$request]) |
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
protected function resolveHandler(array $callback): array |
56
|
|
|
{ |
57
|
1 |
|
$className = $callback[0]; |
58
|
|
|
|
59
|
|
|
try { |
60
|
1 |
|
$handler = App::get($className); |
61
|
1 |
|
} catch (ServiceNotFoundException $e) { |
62
|
1 |
|
$handler = new $className(); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
$callback[0] = $handler; |
66
|
|
|
|
67
|
1 |
|
return $callback; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|