dariorieke/validation

There is no license information available for the latest version (dev-master) of this package.

PHP library to validate data structures

dev-master 2020-08-19 19:24 UTC

This package is auto-updated.

Last update: 2024-12-20 05:36:12 UTC


README

php library for validating data structures

Installation

install via composer

    "require": {
        "dariorieke/validation": "dev-master"
    }

Tests

run tests with the following command inside the repositories root:

./vendor/bin/phpunit  .\tests

Usage

Usage with plain data structures

  1. obtain a validator instance
    use DarioRieke\Validation\ValidatorFactory;
    

$validatorFactory = new ValidatorFactory(); $validator = $validatorFactory->getValidator();

2. set a schema to validate the data against with constraints which describe the structure

use DarioRieke\Validation\Schema; use DarioRieke\Validation\Constraint\Type; use DarioRieke\Validation\Constraint\AllowedChildren; use DarioRieke\Validation\Constraint\Email; use DarioRieke\Validation\Constraint\NotNull;

// we expect an object with 3 properties $schema = new Schema(

new Type('object'), 
new AllowedChildren([ 'name', 'phone', 'email'])

);

// the email property is mandatory and must be a valid email address $schema->addChild('email', new Schema(

new Email(), 
new NotNull()

));

3. validate a given data structure

$data = (object) []; $data->email = "valid@email.com";

$violations = $validator->validate($data);

if(count($violations) > 0) {

foreach ($violations as $violation) {
	echo $violation->getPath();
	echo $violation->getMessage();
}

} else {

//data is valid and can be processed safely

}


### Usage with an object implementing ValidatableInterface

if you want to validate instances of your classes, you can implement the `ValidatableInterface` to store the validation logic inside the class.
This even works with nested properties which implement the `ValidatableInterface`, just add the `Valid` constraint to it.
`ValidatableInterface::getValidationSchema(): SchemaInterface` provides the schema to validate against. 

use DarioRieke\Validation\ValidatableInterface; use DarioRieke\Validation\SchemaInterface; use DarioRieke\Validation\Schema;

/**

  • testclass to validate / class Testclass implements ValidatableInterface { /*

    • @var self */ public $public;

    protected $protected = null;

    private $private = 'private';

    public function __construct($protected) {

    $this->protected = $protected;
    

    }

    public function getValidationSchema(): SchemaInterface {

    $schema = new Schema();
    
    $schema->addChild('protected', new Schema(new Required, new Email));
    $schema->addChild('public', new Schema(new Required, new Valid));
    
    $schema->addChild('private', new Schema(new Required));
    
    return $schema;
    

    } }