Test Failed
Pull Request — master (#87)
by Dmitriy
02:46
created

ExceptionMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
26
    {
27
        try {
28
            return $handler->handle($request);
29
        } catch (ApplicationException $e) {
30
            $code = $this->httpExceptionMapper->getCode($e);
31
32
            return $this->dataResponseFactory->createResponse($e->getMessage(), $code);
33
        } catch (RequestValidationException $e) {
34
            return $this->dataResponseFactory->createResponse($e->getFirstError(), Status::BAD_REQUEST);
35
        }
36
    }
37
}
38