Passed
Push — master ( d1cfc2...9c8db4 )
by Antonio del
01:43
created

SymfonyRouterMiddleware::process()   A

Complexity

Conditions 5
Paths 11

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 11
nop 2
dl 0
loc 23
rs 9.3888
c 0
b 0
f 0
ccs 17
cts 17
cp 1
crap 5
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
18
/**
19
 * @author Antonio del Olmo García <[email protected]>
20
 */
21
class SymfonyRouterMiddleware implements Middleware
22
{
23
    use HasResponseFactory;
24
25
    /**
26
     * @var \Symfony\Component\Routing\Router
27
     */
28
    private $router;
29
30
    /**
31
     * @param \Symfony\Component\Routing\Router $router
32
     */
33 4
    public function __construct(Router $router)
34
    {
35 4
        $this->router = $router;
36 4
    }
37
38
    /**
39
     * Process a request and return a response.
40
     */
41 4
    public function process(Request $request, Handler $handler): Response
42
    {
43
        try {
44 4
            $symfonyRequest = (new HttpFoundationFactory())
45 4
                ->createRequest($request);
46 4
            $this->router->getContext()->fromRequest($symfonyRequest);
47 4
            $route = $this->router
48 4
                ->matchRequest($symfonyRequest);
49 3
        } catch (MethodNotAllowedException $e) {
50 1
            $allows = implode(', ', $e->getAllowedMethods());
51 1
            return $this->createResponse(405, $e->getMessage())
52 1
                    ->withHeader('Allow', $allows);
53 2
        } catch (NoConfigurationException $e) {
54 1
            return $this->createResponse(500, $e->getMessage());
55 1
        } catch (ResourceNotFoundException $e) {
56 1
            return $this->createResponse(404, $e->getMessage());
57
        }
58
59 1
        foreach ($route as $key => $value) {
60 1
            $request = $request->withAttribute($key, $value);
61
        }
62
63 1
        return $handler->handle($request);
64
    }
65
}
66