Issues (12)

Middleware/ValidationExceptionMiddleware.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace App\Application\Middleware;
4
5
use App\Application\Responder\JsonResponder;
6
use App\Module\Validation\Exception\ValidationException;
7
use Psr\Http\Message\ResponseFactoryInterface;
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
13
final readonly class ValidationExceptionMiddleware implements MiddlewareInterface
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 13 at column 6
Loading history...
14
{
15 12
    public function __construct(
16
        private ResponseFactoryInterface $responseFactory,
17
        private JsonResponder $jsonResponder,
18
    ) {
19 12
    }
20
21 12
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
22
    {
23
        try {
24 12
            return $handler->handle($request);
25 8
        } catch (ValidationException $validationException) {
26
            // Create response (status code and header are added later)
27 8
            $response = $this->responseFactory->createResponse();
28
29 8
            $responseData = [
30 8
                'status' => 'error',
31 8
                'message' => $validationException->getMessage(),
32
                // The error format is already transformed to the format that the frontend expects in the exception.
33 8
                'data' => ['errors' => $validationException->validationErrors],
34 8
            ];
35
36 8
            return $this->jsonResponder->encodeAndAddToResponse($response, $responseData, 422);
37
        }
38
    }
39
}
40