samuelgfeller /
slim-starter
| 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 | /** |
||
| 14 | * Middleware for handling validation exceptions. |
||
| 15 | * Documentation: https://samuel-gfeller.ch/docs/Validation. |
||
| 16 | */ |
||
| 17 | final readonly class ValidationExceptionMiddleware implements MiddlewareInterface |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 18 | { |
||
| 19 | 17 | public function __construct( |
|
| 20 | private ResponseFactoryInterface $responseFactory, |
||
| 21 | private JsonResponder $jsonResponder, |
||
| 22 | ) { |
||
| 23 | 17 | } |
|
| 24 | |||
| 25 | 17 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
| 26 | { |
||
| 27 | try { |
||
| 28 | 17 | return $handler->handle($request); |
|
| 29 | 8 | } catch (ValidationException $validationException) { |
|
| 30 | // Create response (status code and header are added later) |
||
| 31 | 6 | $response = $this->responseFactory->createResponse(); |
|
| 32 | |||
| 33 | 6 | $responseData = [ |
|
| 34 | 6 | 'status' => 'error', |
|
| 35 | 6 | 'message' => $validationException->getMessage(), |
|
| 36 | // The error format is already transformed to the format that the frontend expects in the exception. |
||
| 37 | 6 | 'data' => ['errors' => $validationException->validationErrors], |
|
| 38 | 6 | ]; |
|
| 39 | |||
| 40 | 6 | return $this->jsonResponder->encodeAndAddToResponse($response, $responseData, 422); |
|
| 41 | } |
||
| 42 | } |
||
| 43 | } |
||
| 44 |