@@ -28,7 +28,7 @@ use Selective\Validation\ValidationResult;
2828// ...
2929
3030// Get all POST values
31- $data = $request->getParsedBody();
31+ $data = (array) $request->getParsedBody();
3232
3333$validation = new ValidationResult();
3434
@@ -52,23 +52,49 @@ if ($validation->isFailed()) {
5252}
5353```
5454
55- ### PSR-7 Middleware
55+ ### Middleware
5656
57- This validation middleware catches the ` ValidationException ` exception and converts it into a nice JSON response:
57+ The ` ValidationExceptionMiddleware ` PSR-15 middleware catches all exceptions and converts it into a nice JSON response.
58+
59+ #### Slim 4 integration
60+
61+ ``` php
62+ <?php
63+
64+ use Selective\Validation\Middleware\ValidationExceptionMiddleware;
65+ use Slim\Factory\AppFactory;
66+
67+ require_once __DIR__ . '/../vendor/autoload.php';
68+
69+ $app = AppFactory::create();
70+
71+ $app->add(ValidationExceptionMiddleware::class); // <--- add middleware
72+
73+ // ...
74+
75+ $app- >run();
76+ ```
77+
78+ #### Usage
5879
5980``` php
60- use Psr\Http\Message\ResponseInterface as Response;
61- use Psr\Http\Message\ServerRequestInterface as Request;
6281use Selective\Validation\ValidationException;
82+ use Selective\Validation\ValidationResult;
6383
64- // Validation middleware
65- $app->add(function (Request $request, Response $response, $next) {
66- try{
67- return $next($request, $response);
68- } catch (ValidationException $exception) {
69- return $response->withStatus(422)->withJson(['error' => $exception->getValidation()->toArray()]);
70- }
71- });
84+ $validation = new ValidationResult();
85+
86+ // Validate username
87+ if (empty($data->username)) {
88+ $validation->addError('username', 'Input required');
89+ }
90+
91+ // Check validation result
92+ if ($validation->isFailed()) {
93+ $validation->setMessage('Please check your input');
94+
95+ // Trigger the validation middleware
96+ throw new ValidationException($validation);
97+ }
7298```
7399
74100## License
0 commit comments