gd-75 / request-body-validator
A simple PSR-7 compatible request body content validator
Requires
- php: >=7.4
- psr/http-message: ^1.0
Requires (Dev)
- nyholm/psr7: ^1.4
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2025-02-18 04:21:44 UTC
README
A simple PHP library to make the validation of PSR-7 request's parsed bodies less of a pain to write & read 2 month later.
GUARANTEED REGEX FREE!
Note: The doc is not up to date anymore, I'll update it eventually
Example
With the classic isset, empty and is_numeric functions
$pb = $request->getParsedBody(); if( isset($pb["field"], $pb["field1"], $pb["field2"], $pb["field3"], $pb["field4"]) && !empty($pb["field"]) && !empty($pb["field2"]) && is_numeric($pb["field3"]) ){ // Do stuff }
With the validator, using the EXISTS
, EXISTS_NOT_EMPTY
and NUMERIC
criterias.
$validator = new RequestBodyValidator($request->getParsedBody()); if( $validator->validateMultiple(["field1", "field4"], RequestBodyValidator::EXISTS) && $validator->validateMultiple(["field", "field2"], RequestBodyValidator::NOT_EMPTY) && $validator->validateOne("field3", RequestBodyValidator::NUMERIC) ){ // Do stuff }
Given the fact that if
field3
must be numeric, it must also exist. This is taken into account and you don't need to verify thatfield3
exists before verifying that it is numeric. This also applies tofield
andfield2
with their "non-emptiness".
Doc
Or rather a few lines quickly pieced together to show all the options. See example above as well.
Methods
// Constructor, $request is your PSR-7 request object $validator = new RequestBodyValidator($request->getParsedBody()); // validateOne, validates a single field $validator->validateOne($name, $criteria); // validateMultiple, validates multiple fields with the same criteria $validator->validateMultiple([$name, $name1], $criteria);