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