ExceptionMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 16
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 16
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A process() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Http;
6
7
use App\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\Input\Http\InputValidationException;
15
16
final class ExceptionMiddleware implements MiddlewareInterface
17
{
18
    public function __construct(private DataResponseFactoryInterface $dataResponseFactory)
19
    {
20
    }
21
22
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
23
    {
24
        try {
25
            return $handler->handle($request);
26
        } catch (ApplicationException $e) {
27
            return $this->dataResponseFactory->createResponse($e->getMessage(), $e->getCode());
28
        } catch (InputValidationException $e) {
29
            return $this->dataResponseFactory->createResponse(
30
                $e->getResult()->getErrorMessages()[0],
31
                Status::BAD_REQUEST
32
            );
33
        }
34
    }
35
}
36