Passed
Pull Request — master (#7)
by Antonio del
20:40 queued 17:41
created

SymfonyRouterMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 20
c 3
b 0
f 0
dl 0
loc 35
ccs 20
cts 20
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 24 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
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