-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added validation exception middleware and validation test [SLE-197]
- Loading branch information
1 parent
20cfdbb
commit 2eb03a8
Showing
3 changed files
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
src/Application/Middleware/ValidationExceptionMiddleware.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<?php | ||
|
||
namespace App\Application\Middleware; | ||
|
||
use App\Application\Responder\JsonEncoder; | ||
use App\Domain\Exception\ValidationException; | ||
use Psr\Http\Message\ResponseFactoryInterface; | ||
use Psr\Http\Message\ResponseInterface; | ||
use Psr\Http\Message\ServerRequestInterface; | ||
use Psr\Http\Server\MiddlewareInterface; | ||
use Psr\Http\Server\RequestHandlerInterface; | ||
|
||
final readonly class ValidationExceptionMiddleware implements MiddlewareInterface | ||
{ | ||
public function __construct( | ||
private ResponseFactoryInterface $responseFactory, | ||
private JsonEncoder $jsonEncoder, | ||
) { | ||
} | ||
|
||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | ||
{ | ||
try { | ||
return $handler->handle($request); | ||
} catch (ValidationException $validationException) { | ||
// Create response (status code and header are added later) | ||
$response = $this->responseFactory->createResponse(); | ||
|
||
$responseData = [ | ||
'status' => 'error', | ||
'message' => $validationException->getMessage(), | ||
// The error format is already transformed to the format that the frontend expects in the exception. | ||
'data' => ['errors' => $validationException->validationErrors], | ||
]; | ||
|
||
return $this->jsonEncoder->encodeAndAddToResponse($response, $responseData, 422); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters