Passed
Pull Request — master (#87)
by Dmitriy
02:45
created

ExceptionMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 18
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 18
ccs 7
cts 7
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 10 3
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Infrastructure\Http\Middleware;
6
7
use App\Application\Exception\ApplicationException;
8
use App\Infrastructure\Http\HttpExceptionMapper;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Yiisoft\DataResponse\DataResponseFactoryInterface;
14
use Yiisoft\Http\Status;
15
use Yiisoft\RequestModel\RequestValidationException;
16
17
final class ExceptionMiddleware implements MiddlewareInterface
18
{
19
    public function __construct(
20
        private DataResponseFactoryInterface $dataResponseFactory,
21
        private HttpExceptionMapper $httpExceptionMapper,
22
    ) {
23
    }
24
25 12
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
26
    {
27
        try {
28 12
            return $handler->handle($request);
29 2
        } catch (ApplicationException $e) {
30 1
            $code = $this->httpExceptionMapper->getCode($e);
31
32 1
            return $this->dataResponseFactory->createResponse($e->getMessage(), $code);
33 1
        } catch (RequestValidationException $e) {
34 1
            return $this->dataResponseFactory->createResponse($e->getFirstError(), Status::BAD_REQUEST);
35
        }
36
    }
37
}
38