PHP Classes

File: README.md

Recommend this page to a friend!
  Classes of Smoren Freelight   PHP Validator Library   README.md   Download  
File: README.md
Role: Documentation
Content type: text/markdown
Description: Documentation
Class: PHP Validator Library
Validate an array of values using multiple rules
Author: By
Last change:
Date: 1 year ago
Size: 3,283 bytes
 

Contents

Class file image Download

PHP Validation Tools

Packagist PHP Version Support Scrutinizer Code Quality Coverage Status Build and test License: MIT

How to install to your project

composer require smoren/validator

Usage

use Smoren\Validator\Factories\Value;
use Smoren\Validator\Exceptions\ValidationError;

$rule = Value::container()
    ->array()
    ->hasAttribute('id', Value::integer()->positive())
    ->hasAttribute('probability', Value::float()->between(0, 1))
    ->hasAttribute('vectors', Value::container()->array()->allValuesAre(
        Value::container()
            ->array()
            ->lengthIs(Value::integer()->equal(2))
            ->allValuesAre(Value::integer())
    ));

$validInput = [
    'id' => 13,
    'probability' => 0.92,
    'vectors' => [[1, 2], [3, 4], [5, 6]],
];

try {
    $rule->validate($validInput);
} catch (ValidationError $e) {
    // Input is valid so this block is unreachable.
}

$invalidInput = [
    'id' => '13',
    'probability' => 1.92,
    'vectors' => [[1, 2.1], [3, 4], [5, 6]],
];

try {
    $rule->validate($invalidInput);
} catch (ValidationError $e) {
    // Input is invalid so we catch the exception.
    print_r($e->getViolatedRestrictions());
    /*
    [
        ['attribute_is', [
            'attribute' => 'id',
            'rule' => 'integer',
            'violated_restrictions' => [
                ['integer', []]
            ]
        ]],
        ['attribute_is', [
            'attribute' => 'probability',
            'rule' => 'float',
            'violated_restrictions' => [
                ['between', [
                    'start' => 0,
                    'end' => 1
                ]]
            ]
        ]],
        ['attribute_is', [
            'attribute' => 'vectors',
            'rule' => 'container',
            'violated_restrictions' => [
                ['all_values_are', [
                    'rule' => 'container',
                    'violated_restrictions' => [
                        ['all_values_are', [
                            'rule' => 'integer',
                            'violated_restrictions' => [
                                ['integer', []]
                            ]
                        ]]
                    ]
                ]]
            ]
        ]]
    ]
    */
}

Unit testing

composer install
composer test-init
composer test

Standards

PHP Validator Tools conforms to the following standards:

License

PHP Validation Tools is licensed under the MIT License.