benycode / slim-request-validation
A slim middleware for HTTP request validation based on Respect/Validation
v1.4.8
2024-04-03 11:14 UTC
Requires
- php: ^7.4 || ^8.0
- benycode/slim-request-accept-header: ^1.0
- psr/http-message: ^1.0
- respect/validation: ^2.2
- slim/psr7: ^1.3
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.4.1
- php-di/php-di: ^6.3
- phpunit/phpunit: ^8.0 || ^9.0
- scrutinizer/ocular: ~1.1
- slim/http: ^1.2
- slim/slim: ~4.0
README
A Request validation library for the Slim 4 Framework. It uses respect-validation library.
Table of contents
Install
Via Composer
$ composer require benycode/slim-request-validation
Requires Slim 4.
Usage
Create a Rule class:
use BenyCode\Slim\Validation\Rule\RequestValidationRuleInterface; use Respect\Validation\Validator; final class AnyRuleClass implements RequestValidationRuleInterface { public function rules(): array { return [ 'name' => Validator::alpha(), 'url' => Validator::filterVar(FILTER_VALIDATE_URL), ]; } public function messages(): array { return [ 'filterVar' => '{{name}} must be valid modified message.', ]; } }
add a Middlewares to route:
use BenyCode\Slim\Validation\Middleware\RequestValidationExceptionMiddleware; use BenyCode\Slim\Validation\Transformer\RequestValidatorTransformFactory; use BenyCode\Slim\Validation\Encoder\JsonEncoder; $app = new \Slim\App(); $app->post('/api/any_end_point',function ($req, $res, $args) { }) ->add(new RequestValidationExceptionMiddleware(new RequestValidatorTransformFactory(), new JsonEncoder())) ->add(new RequestValidation([ new AnyRuleClass(), ])) ; $app->run();
keep a clean code and split the rules:
use BenyCode\Slim\Validation\Middleware\RequestValidationExceptionMiddleware; use BenyCode\Slim\Validation\Transformer\RequestValidatorTransformFactory; use BenyCode\Slim\Validation\Encoder\JsonEncoder; $app = new \Slim\App(); $app->post('/api/any_end_point',function ($req, $res, $args) { }) ->add(new RequestValidationExceptionMiddleware(new RequestValidatorTransformFactory(), new JsonEncoder())) ->add(new RequestValidation([ new AnyRuleClass(), new AppendedRuleClass(), new AppendedRule2Class(), new AppendedRule3Class(), .... ])) ; $app->post('/api/any_end_point2',function ($req, $res, $args) { }) ->add(new RequestValidationExceptionMiddleware(new RequestValidatorTransformFactory(), new JsonEncoder())) ->add(new RequestValidation([ new AnyRuleClass(), new AppendedRule3Class(), .... ])) ; $app->run();