1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace DelOlmo\Middleware; |
6
|
|
|
|
7
|
|
|
use Middlewares\Utils\Factory; |
8
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
9
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
11
|
|
|
use Psr\Http\Server\MiddlewareInterface as Middleware; |
12
|
|
|
use Psr\Http\Server\RequestHandlerInterface as Handler; |
13
|
|
|
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; |
14
|
|
|
use Symfony\Component\Routing\Exception\MethodNotAllowedException; |
15
|
|
|
use Symfony\Component\Routing\Exception\NoConfigurationException; |
16
|
|
|
use Symfony\Component\Routing\Exception\ResourceNotFoundException; |
17
|
|
|
use Symfony\Component\Routing\Router; |
18
|
|
|
use function implode; |
19
|
|
|
|
20
|
|
|
class SymfonyRouterMiddleware implements Middleware |
21
|
|
|
{ |
22
|
|
|
private ResponseFactoryInterface $responseFactory; |
23
|
|
|
|
24
|
|
|
private Router $router; |
25
|
|
|
|
26
|
6 |
|
public function __construct( |
27
|
|
|
Router $router, |
28
|
|
|
?ResponseFactoryInterface $responseFactory = null |
29
|
|
|
) { |
30
|
6 |
|
$this->router = $router; |
31
|
|
|
|
32
|
6 |
|
$this->responseFactory = $responseFactory ?? |
33
|
5 |
|
$this->getDefaultResponseFactory(); |
34
|
6 |
|
} |
35
|
|
|
|
36
|
6 |
|
public function process(Request $request, Handler $handler) : Response |
37
|
|
|
{ |
38
|
|
|
try { |
39
|
6 |
|
$symfonyRequest = (new HttpFoundationFactory()) |
40
|
6 |
|
->createRequest($request); |
41
|
|
|
|
42
|
6 |
|
$this->router->getContext()->fromRequest($symfonyRequest); |
43
|
|
|
|
44
|
|
|
/** @psalm-var array<string,mixed> $route */ |
45
|
6 |
|
$route = $this->router |
46
|
6 |
|
->matchRequest($symfonyRequest); |
47
|
4 |
|
} catch (MethodNotAllowedException $e) { |
48
|
1 |
|
$allows = implode(', ', $e->getAllowedMethods()); |
49
|
|
|
|
50
|
1 |
|
return $this->responseFactory |
51
|
1 |
|
->createResponse(405, $e->getMessage()) |
52
|
1 |
|
->withHeader('Allow', $allows); |
53
|
3 |
|
} catch (NoConfigurationException $e) { |
54
|
1 |
|
return $this->responseFactory |
55
|
1 |
|
->createResponse(500, $e->getMessage()); |
56
|
2 |
|
} catch (ResourceNotFoundException $e) { |
57
|
2 |
|
return $this->responseFactory |
58
|
2 |
|
->createResponse(404, $e->getMessage()); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** @psalm-var mixed $value */ |
62
|
2 |
|
foreach ($route as $key => $value) { |
63
|
1 |
|
$request = $request->withAttribute($key, $value); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
return $handler->handle($request); |
67
|
|
|
} |
68
|
|
|
|
69
|
5 |
|
private function getDefaultResponseFactory() : ResponseFactoryInterface |
70
|
|
|
{ |
71
|
5 |
|
return Factory::getResponseFactory(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|