PHP code example of guide42 / plan

1. Go to this page and download the library: Download guide42/plan library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

guide42 / plan example snippets


use plan\{Schema, MultipleInvalid, assert as v, filter as f};

$userSchema = new Schema(array(
    'id' => v\int(),
    'type' => v\any('user', 'admin'),
    'name' => v\all(
        v\length(4, 20),
        f\intl\alnum()
    ),
));

$_POST = ['id' => 3004, 'type' => 'user', 'name' => 'John'];

try {
    $user = $userSchema($_POST);
} catch (MultipleInvalid $errors) {
    $messages = $errors->getMessages();
}

$plan = new Schema('Hello World');

assert('Hello World' === $plan('Hello World'));

$plan = new Schema(42);
$plan(42);

try {
    $plan(10);
} catch (MultipleInvalid $errors) {
    assert('[ 10 is not 42 ]' === $errors->getMessage());
}

$plan = new Schema([1, 'one']);
$plan([1]);
$plan([1, 'one', 1, 1, 'one', 1]);

$plan = new Schema([]);
$plan(['anything', 123, true]);

$plan = new Schema(v\type('integer'));
$plan(123);

try {
    $plan('123');
} catch (MultipleInvalid $errors) {
    assert('[ "123" is not integer ]' === $errors->getMessage());
}

$plan = new Schema(v\dict(array(
    'id' => v\optional(v\int()),
    'name' => v\optional(v\str()),
)));
$plan(array('id' => 3004));
$plan(array('name' => 'John'));
$plan(array());

    $plan = new Schema([v\str(), array(
        'name'  => v\str(),
        'email' => v\email(),
    )]);
    $plan([
        array('name' => 'Kevin', 'email' => '[email protected]'),
        array('name' => 'Jane', 'email' => '[email protected]'),
        'John Doe <[email protected]>',
    ]);
    

$dict = array('name' => 'John', 'age' => 42);
$plan = new Schema($dict);

try {
    $plan(array('age' => 42));
} catch (MultipleInvalid $errors) {
    assert('{ [name]: null is not string }' === $errors->getMessage());
}

try {
    $plan(array('name' => 'John', 'age' => 42, 'sex' => 'male'));
} catch (MultipleInvalid $errors) {
    assert('{ Extra key sex not allowed }' === $errors->getMessage());
}

$$extra    = true;  // Accept extra keys

$dict = array('name' => 'John', 'age' => 42);
$plan = new Schema(v\dict($dict, $ot be validated
));

$dict = array('name' => 'John', 'age' => 42);
$plan = new Schema(v\dict($dict, ['age'], ['sex']));
$plan(array('name' => 'John', 'age' => 42, 'sex' => 'male'));

try {
    $plan(array('name' => 'John', 'hobby' => 'sailing'));
} catch (MultipleInvalid $errors) {
    assert('{ Extra key hobby not allowed, [age]: Required age not provided }' === $errors->getMessage());
}

$extra = array('dob' => v\instance('\\DateTime'));

$dict = array('name' => 'John', 'age' => 42);
$plan = new Schema(v\dict($dict, true, $extra));
$plan(array('name' => 'John', 'age' => 42, 'dob' => new \DateTime));

try {
    $plan(array('name' => 'John', 'age' => 42, 'dob' => '1970-01-01'));
} catch (MultipleInvalid $errors) {
    assert('{ Extra key dob is not valid: Expected \DateTime (is not an object) }' === $errors->getMessage());
}

$schema = v\keys(function(array $keys) {
    return array_filter($keys, function($key) {
        return $key === 'two';
    });
});

$result = $schema([
    'one' => 1,
    'two' => 2,
]);

assert($result === [ 'two' => 2 ]);

$structure = array('name' => v\str());
$class     = 'stdClass';
$byref     = true;

$plan = new Schema(v\object($structure, $class, $byref));
$plan((object) array('name' => 'John'));

try {
    $plan((object) array('name' => false));
} catch (MultipleInvalid $errors) {
    assert('{ [name]: false is not string }' === $errors->getMessage());
}

$plan = new Schema(array(
    'Connection' => v\any('ethernet', 'wireless'),
));
$plan(array('Connection' => 'ethernet'));
$plan(array('Connection' => 'wireless'));

try {
    $plan(array('Connection' => 'any'));
} catch (MultipleInvalid $errors) {
    assert('{ [Connection]: No valid value found }' === $errors->getMessage());
}

$plan = new Schema(v\all(v\str(), v\length(3, 17)));
$plan('Hello World');

try {
    $plan('No');
} catch (MultipleInvalid $errors) {
    assert('[ Value must be at least 3 ]' === $errors->getMessage());
}

$plan = new Schema(v\not(v\str()));
$plan(true);
$plan(123);

try {
    $plan('fail');
} catch (MultipleInvalid $errors) {
    assert('[ Validator passed ]' === $errors->getMessage());
}

$class = 'stdClass';
$plan = new Schema(v\iif(null !== $class,
    v\instance($class),
    v\type('object')
));

$plan(new stdClass);

try {
    $plan(new Exception('Arr..'));
} catch (MultipleInvalid $errors) {
    assert('[ Expected stdClass (is Exception) ]' === $errors->getMessage());
}

$plan = new Schema(v\length(2, 4));
$plan('abc');
$plan(['a', 'b', 'c']);

try {
    $plan('hello');
} catch (MultipleInvalid $errors) {
    assert('[ Value must be at most 4 ]' === $errors->getMessage());
}

$plan = new Schema(v\validate('email'));
$plan('[email protected]');

try {
    $plan('john(@)example.org');
} catch (MultipleInvalid $errors) {
    assert('[ Expected email ]' === $errors->getMessage());
}

$plan = new Schema(f\type('int'));
$data = $plan('123 users');

assert(123 === $data);

$plan = new Schema(f\sanitize('email'));
$data = $plan('(john)@example.org');

assert('[email protected]' === $data);

$plan = new Schema(f\datetime('Y-m-d H:i:s'));
$data = $plan('2009-02-23 23:59:59')->format('m-d');

assert('02-23' === $data);

$plan = new Schema(f\str\nullempty());
$data = $plan('');

assert(null === $data);

$plan = new Schema(f\str\strip("\t"));
$data = $plan('\t  Hello World\t');

assert('  Hello World' === $data);

$lower      = true; // all lower-case characters
$upper      = true; // all upper-case characters
$number     = true; // all numbers
$whitespace = true; // the only one not language dependant

$plan = new Schema(f\intl\chars($lower, $upper, $number, $whitespace));
$data = $plan('Hello World ☃!!1');

assert('Hello World 1' === $data);

$passwordStrength = function($data, $path = null)
{
    $type = v\str(); // Use another validator to check that `$data` is
    $data = $type($data); // an string, if not will throw an exception.

    // Because we are going to throw more than one error, we will
    // accumulate in this variable.
    $errors = [];

    if (strlen($data) < 8) {
        $errors[] = new Invalid('Must be at least 8 characters');
    }

    if (!preg_match('/[A-Z]/', $data)) {
        $errors[] = new Invalid('Must have at least one uppercase letter');
    }

    if (!preg_match('/[a-z]/', $data)) {
        $errors[] = new Invalid('Must have at least one lowercase letter');
    }

    if (!preg_match('/\d/', $data)) {
        $errors[] = new Invalid('Must have at least one digit');
    }

    if (count($errors) > 0) {
        throw new MultipleInvalid($errors);
    }

    // If everything went OK, we return the data so it can continue to be
    // checked by the chain.
    return $data;
};

$validator = new Schema(v\all(v\str(), $passwordStrength, v\not('hunter2')));
$validated = $validator('heLloW0rld');