PHP code example of jsl / ensure

1. Go to this page and download the library: Download jsl/ensure 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/ */

    

jsl / ensure example snippets


use Jsl\Ensure\Ensure;

$values = [
    'name' => 'Mr Magoo',
    'age'  => 77,
];

$rules = [
    'name' => ['ure = new Ensure($rules, $values);

// Validate the values against the rules
$result = $ensure->validate();

// Check if the validation was successful
$result->isValid(); // Returns true or false

// If validation failed, get array of validation errors
print_r($result->getErrors());

// Returns:
// 
// Array
// (
//     [name] => Array
//         (
//             [0] => Size of name must be at least 20
//         )
//     [age] => Array
//         (
//             [0] => Size of age must be at least 80
//         )
// )

$rules = [
    'name' => [' 'type' => 'integer', 'minSize' => 80],
];

// Pass them through the constructor
$ensure = new Ensure($rules, $values);

// Add/replace a rule on an existing instance
// setFieldRule(string $field, string $rule, ...$args)
$ensure->setFieldRule('name', 'minSize', 10);

// Add/replace multiple rules on an existing instance
// setFieldRules(string $field, array $rules)
$ensure->setFieldRules('age', ['type' => 'string', 'minSize' => 70]);

// Remove a field rule
// removeRule(string $field, string $rule)
$ensure->removeFieldRule('age', 'type');

$values = [
    'name' => 'Mr Magoo',
    'age'  => 77,
];

// Pass them through the constructor
// You can pass $_POST or $_GET directly as well
$ensure = new Ensure($rules, $values);

// Add/replace a value on an existing instance
// seFieldValue(string $field, mixed $value)
$ensure->setFieldValue('name', 'Mrs Magoo');

// Replace all values
// replaceValues(array $values)
$ensure->replaceValues([
    'name' => 'Mrs Magoo', 
    'age' => 70
]);

// Validate the values against the rules and get the result
$result = $ensure->validate();

// Check if the validation was successful
$result->isValid(); // Returns true or false

// Getting potential errors (returns all failed rules for the fields)
// This will return an array [fieldname => [error1, error2, ...]]
$errors = $result->getErrors();

// To only get the first failed rule, pass "true" to the method
// This will return an array [fieldname => error1, fieldname2 => error1, ...]
$errors = $result->getErrors(true);

// Set the default error template for a specific rule
// This will replace the error template for this rule for all fields
$ensure->setRuleTemplate('rule', '{field} has failed {a:0}');

// Set the default error template for a specific rule for a specific field
// This will only replace the error template for this rule for the specific field
$ensure->setFieldRuleTemplate('field', 'rule', '{field} has failed {a:0}');

// Set a single error template for a specific field, regardless of which rule failed
// Note: This will only replace rule templates, not field rule templates set with setFieldRuleTemplate()
$ensure->setFieldTemplate('field', 'rule', '{field} has failed {a:0}');

// To remove a previously added error template, pass in null as the message
// This works on all the above methods
$ensure->setRuleTemplate('rule', null);

$template = '{field} must be {a:0}';

// {field} will be replaced with the field name
// {a:0} will be replaced with the value from the first argument
// {a:1} will be replaced with the value from the second argument
// ...you can have as many `{a:x}` as there are arguments for the rule

// Set multiple fancy names in one go
$ensure->setFancyNames([
    'name' => 'The name',
    'age' => 'The age',
]);

// Either through the rules array
$rules = [
    'name' => [
        'any other rule
$ensure->setFieldRule('fieldname', 'as', 'Fancy field name');

$ensure->addValidator('between', function ($value, $min, $max): bool {
    return $value >= $min && $value <= $max;
});

class BetweenValidator
{
    public function __invoke($value, $min, $max): bool
    {
        return $value >= $min && $value <= $max;;
    }
}

$ensure->addValidator('between', BetweenValidator::class);

// You can also pass it as an instance

$ensure->addValidator('between', new BetweenValidator);

class MyValidators
{
    public function myBetweenMethod($value, $min, $max): bool
    {
        return $value >= $min && $value <= $max;
    }
}

$ensure->addValidator('between', [MyValidators::class, 'myBetweenMethod']);

// You can also use an instance

$ensure->addValidator('between', [new MyValidators, 'myBetweenMethod']);

function myBetweenFunc($value, $min, $max): bool
{
    return $value >= $min && $value <= $max;
}

$ensure->addValidator('between', 'myBetweenFunc');

$rule = [
    'theValueField' => [
        'sameAsField' => ['anotherValueField']
    ],
];

class AreFieldsSameValidator extends \Jsl\Ensure\Abstracts\Validator
{
    /**
     * Check if two values are the same
     *
     * @param mixed $value  The value
     * @param string $field The name of the other field
     *
     * @return bool
     */
    public function __invoke($value, $field): bool
    {
        return $value === $this->getValue($field);
    }


    /**
     * For classes implementing the ValidatorInstance,
     * we should add the error template like this
     *
     * @return string
     */
    public function getTemplate(): string
    {
        return '{field} must be the same as {a:0}';
    }
}

$ensure->addValidator('sameAsField', AreFieldsSameValidator::class);

return new $className;

$ensure->setClassResolver(function (string $className) use ($yourContainer) {
    return $yourContainer->has($className)
        ? $yourContainer->get($className)
        : new $className;
});

use Jsl\Ensure\EnsureFactory;

$factory = new EnsureFactory;

$factory->setFieldTemplate(...)
    ->setFieldRuleTemplate(...)
    ->setRuleTemplate(...)
    ->setClassResolver(...)
    ->addValidator(...);

// To get an Ensure instance that inherits those settings
$ensure = $factory->create($rules, $data);

$factory->addRuleset('myRuleset', [
    'name' => [
        'red',
        'minSize' => 18,
    ],
]);

$ensure = $factory->create('myRuleset', $_POST);