Passed
Pull Request — master (#87)
by Dmitriy
12:42
created

ExceptionMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 17
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

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