graze/config-validation

validate and populate arrays and objects

0.2 2018-08-06 14:18 UTC

This package is auto-updated.

Last update: 2024-11-24 04:57:58 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Config Validation checks an input against a code defined schema for validation using short notation syntax.

It then populates optional fields with default data.

Install

Via Composer

composer require graze/config-validation

Usage

Long path definition

use Respect\Validation\Validator as v;

$validator = (new ArrayValidator())
    ->required('key', v::stringType())
    ->optional('parent.child', v::intVal(), 1)
    ->optional('parent.second', v::stringType()->date());

Using children

$validator = Validator::arr()
    ->required('key', v::stringType())
    ->addChild('parent', Validator::arr()
        ->optional('child', v::intVal(), 1)
        ->optional('second', v::stringType()->date()
    );

Validating with your validator

function thing (array $input) {
    return $validator->validate($input);
}

thing(['key' => 'value'])
// ['key' => 'value', 'parent' => ['child' => 1, 'second' => null]]
thing();
// throws new ConfigValidationFailed
thing(['key' => 'input', ['parent' => ['child' => 2]])
// ['key' => 'input', ['parent' => ['child' => 2, 'second' => null]]
thing(['key' => 'input', ['parent' => ['second' => '111']])
// throws new ConfigValidationFailed('expected data for parent.second')
thing(['key' => 'input', ['parent' => ['second' => 

Validating array items with variable keys

$childValidator = Validate::object()
    ->required('key->item', v::intVal()->min(2)->max(4))
    ->optional('key->second', v::stringType(), 'name');
$validator = Validate::object()
    ->required('items', v::arrayVal()->each(
        $childValidator->getValidator()
    ));

function thing ($input) {
    return $validator->validate($input);
}

thing((object) ['items' => [
    (object) ['key' => 3],
    ]]);
// (object) ['items' => [
//     (object) ['key' => (object) ['item' => 3, 'second' => 'name']]
// ]]

Testing

make build test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email security@graze.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.