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

ExceptionMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 19
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 19
ccs 9
cts 9
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 10 3
A __construct() 0 5 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 12
    public function __construct(
20
        private DataResponseFactoryInterface $dataResponseFactory,
21
        private HttpExceptionMapper          $httpExceptionMapper,
22
    )
23
    {
24 12
    }
25
26 12
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
27
    {
28
        try {
29 12
            return $handler->handle($request);
30 2
        } catch (ApplicationException $e) {
31 1
            $code = $this->httpExceptionMapper->getCode($e);
32
33 1
            return $this->dataResponseFactory->createResponse($e->getMessage(), $code);
34 1
        } catch (RequestValidationException $e) {
35 1
            return $this->dataResponseFactory->createResponse($e->getFirstError(), Status::BAD_REQUEST);
36
        }
37
    }
38
}
39