samuelgfeller /
slim-example-project
| 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
Bug
introduced
by
Loading history...
|
|||
| 14 | { |
||
| 15 | 203 | public function __construct( |
|
| 16 | private ResponseFactoryInterface $responseFactory, |
||
| 17 | private JsonResponder $jsonResponder, |
||
| 18 | ) { |
||
| 19 | 203 | } |
|
| 20 | |||
| 21 | 203 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
| 22 | { |
||
| 23 | try { |
||
| 24 | 203 | return $handler->handle($request); |
|
| 25 | 62 | } catch (ValidationException $validationException) { |
|
| 26 | // Create response (status code and header are added later) |
||
| 27 | 26 | $response = $this->responseFactory->createResponse(); |
|
| 28 | |||
| 29 | 26 | $responseData = [ |
|
| 30 | 26 | 'status' => 'error', |
|
| 31 | 26 | 'message' => $validationException->getMessage(), |
|
| 32 | // The error format is already transformed to the format that the frontend expects in the exception. |
||
| 33 | 26 | 'data' => ['errors' => $validationException->validationErrors], |
|
| 34 | 26 | ]; |
|
| 35 | |||
| 36 | 26 | return $this->jsonResponder->encodeAndAddToResponse($response, $responseData, 422); |
|
| 37 | } |
||
| 38 | } |
||
| 39 | } |
||
| 40 |