dev-master
9999999-devValidate custom data classes (framework agnostic)
MIT
The Requires
- respect/validation ^1.0
- php >=5.6
- psr/http-message ^1.0
The Development Requires
Wallogit.com
2017 © Pedro Peláez
Validate custom data classes (framework agnostic)
A library to validate structured data against a schema., (*1)
This library is currently actively developed, and changed to its API should be expected. If you want to use it in production, please check the status again in a few weeks..., (*3)
Most common web applications handle structural input data. Examples are:, (*4)
In all cases, the data has to be validated. Often enough, this validation is mixed with other tasks, maybe even with business logic. The goal of this library is to separate the validation step from the business logic., (*5)
How does it work? This library provides:, (*6)
The intended usage is:, (*7)
For "low level validations", i.e. to validate single scalar values, the Respect Validation Library is used. There are no dependencies to any full stack frameworks. The library is desiged to be easily integrated into any application structure., (*8)
use Ckr\Validata\Schema; use Ckr\Validata\Validator; use Respect\Validation\Rules; function action() { $schema = getValidationSchema(); $result = Validator::run($schema, $_POST); if ($result->hasErrors()) { handleErrors($result->getErrors()); } else { handleRequest($result->getValidData()); } } /** * Builds the validation schema for `action` */ function getValidationSchema() { $mainSchema = new Schema\Map(); $emailSchema = new Schema\Scalar(new Rules\Email()); $usernameSchema = new Schema\Scalar(new Rules\Alnum()); $mainSchema->property('email', $emailSchema); $mainSchema->property('username', $usernameSchema); return $mainSchema; } function handleErrors(array $errors) { // TODO handle errors... } function handleRequest(array $validData) { // TODO implement the actual business logic }
While this looks like lots of code, much of it is always the same and can be abstracted. How this is done, varies with the framework or application structure., (*9)
Especially the error handling can probably be reused for all actions of the same API or application, as the errors have detailed information, that can easily be transformed in a JSON Response (or any other structured data format)., (*10)
The creation of the schema is a bit tedious. I will probably provide builders or similar helpers in near future to make composing various subschemas easier., (*11)
Validate custom data classes (framework agnostic)
MIT