1. Go to this page and download the library: Download marwanalsoltany/mighty 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/ */
marwanalsoltany / mighty example snippets
use MAKS\Mighty\Validator;
$validator = new Validator();
$validator
->setData([
'name' => 'John Doe',
'username' => 'john.doe',
'password' => 'Super@Secret#123',
'email' => '[email protected]',
'hobbies' => ['coding', 'design', 'sports'],
])
->setValidations([
// >string()->min(8),
// validations.array}&(string&min:3))
// hobby can be null or a string with at least 3 characters if hobbies is an array
'hobbies.*' => $validator
->validation()
->null()
->or()
->group(fn ($validation) => $validation
->if('${hobbies.validations.array}')
->open()
->string()
->min(3)
->close()
),
])
->validate();
$result = $validator->isOK(); // boolean result of the overall validation result
$errors = $validator->getErrors(); // an array of results of validations that failed
$results = $validator->getResults(); // an array of results of all validations
$validator->check(); // void or throws an exception with a nicely formatted message of what exactly went wrong
use MAKS\Mighty\Validation\Strategy;
use MAKS\Mighty\Validation\Behavior;
use MAKS\Mighty\Validation\Operator;
use MAKS\Mighty\Validation\Constraint;
use MAKS\Mighty\Validation\Constraint as Assert;
use MAKS\Mighty\Validation\Constraint\ValidatableObjectInterface;
use MAKS\Mighty\Validation\Constraint\ValidatableObjectTrait;
class ValidatableObject implements ValidatableObjectInterface
{
use ValidatableObjectTrait;
#[Assert\Rule\Equals('CONST')]
public const CONST = 'CONST';
#[Assert\Rule\In(['STATIC', 'VAR'])]
public static $static = 'VAR';
#[Assert\Rule\StringConstraint]
#[Assert\Rule\StringCharset('UTF-8')]
#[Assert\Rule\Between(3, 99)]
public $default = 'DEFAULT';
#[Assert\Rule\StringConstraint]
#[Assert\Rule\StringContains('<element>')]
#[Assert\Rule\Xml]
public $xml = '<?xml version="1.0"
// check out the previous snippet see the used constraints
$object = new ValidatableObject();
$object->object = new class implements ValidatableObjectInterface {
use ValidatableObjectTrait;
// some properties and their validation constraints ...
};
$object->default = null; // this must be a string
$object->check();
// ValidationFailedException::class
// Data failed to pass the validation.
// (01) The value (null) of the "ValidatableObject->default" property failed to pass the validation [string]. Problem: Value must be a string.
// (02) The value (null) of the "ValidatableObject->default" property failed to pass the validation [string.charset:"UTF-8"]. Problem: Value must be encoded in one of the following charsets: ["UTF-8"].
// (03) The value (null) of the "ValidatableObject->default" property failed to pass the validation [between:3,99]. Problem: Value must be between 3 and 99 or have a value/count/length that is between 3 and 99.
// (04) The return value (null) of the "ValidatableObject->getDefault()" method failed to pass the validation [callback]. Problem: Data is not scalar.
// (05) The return value (null) of the "ValidatableObject->getDefault()" method failed to pass the validation [string&min:3]. Problems: Must be string; Must be longer than 3.
use MAKS\Mighty\Validation;
// the validation expression: `:
$validation = (new Validation())->
use MAKS\Mighty\Validator;
$result = ($validator = new Validator())
->validateOne(
'123',
$validator
->validation()
// can be an integer or float or a string that is numeric
// this example is only for demonstration only,
// the same result can be achieved using numeric() only
->integer()->or()->float()->or()->group(
fn ($validation) => $validation->string()->and()->numeric()
)
)
->toArray();
// $result would look something like this:
[
'value' => '123',
'result' => true,
'validations' => [
'integer' => false,
'float' => false,
'string' => true,
'numeric' => true,
],
'errors' => [],
'metadata' => [
'basis' => 'integer|float|(string&numeric)',
'rules' => 'integer|float|(string&numeric)',
'expression' => '0|0|(1&1)',
],
];
// you can also simply use the static helper Validator::validateData($data, $validation);
use MAKS\Mighty\Validator;
use App\Service\HaveIBeenPwnedService as PasswordService;
$validator = new Validator();
$data = [
'name' => 'John Doe',
'age' => 32,
'email' => '[email protected]',
'username' => 'john.doe',
'password' => 'Secret@123',
'image' => '/path/to/image.png',
'submission' => 'now',
'consent' => 'yes',
'data' => [
'nickname' => 'JOE',
'number' => 7,
'hobbies' => [
'coding',
'cooking',
'reading',
]
],
];
$validations = [
'name' => $validator->validation()->ck ist not possible, it -> 'image' => 'Image',
'data' => 'Data',
'data.*' => 'Value of data',
'consent' => 'Consent',
];
$messages = [
'*' => [ // this will be expanded for all fields
' 'string.charset' => true,
],
'errors' => [],
'metadata' => [
'basis' => '!
use MAKS\Mighty\Validator;
use MAKS\Mighty\Rule;
$validator = new Validator();
// adding a new rule
$validator->addRule(
(new Rule())
->name('equals')
->arguments(['string'])
->callback(fn (string $input, mixed $expected): bool => $input == $expected)
->parameters(['@input', '@arguments.0'])
->comparison(['@output', '===', true])
->example('equals:value')
->description('Asserts that the input is equal to the given value.')
);
// adding a new rule alias
$validator->addRuleAlias('eq', 'equals');
// adding a new rules macro
$validator->addRuleMacro('gmail', 'string&email&matches:"/@gmail\.com$/i"');
$results = $validator->validateAll(
[
'name' => 'John',
'email' => '[email protected]',
],
[
'name' => 'eq:John',
'email' => ',
'rules' => '
declare(strict_types=1);
namespace App\Validation\Constraint;
use Attribute;
use MAKS\Mighty\Rule;
use MAKS\Mighty\Result;
use MAKS\Mighty\Validation\Strategy;
use MAKS\Mighty\Validation\Constraint;
use MAKS\Mighty\Validation\Constraint\ValidatesOne;
// use the ValidatesMany interface if your Constraint returns a collection of Result objects
use MAKS\Mighty\Validation\Constraint\ValidatesMany;
#[Attribute(
Attribute::TARGET_PROPERTY |
Attribute::TARGET_METHOD
)]
class MyCustomConstraint extends Constraint implements ValidatesOne
{
public function __construct(
?string $message = null,
Strategy $strategy = Strategy::FailFast,
) {
parent::__construct(
validation: 'app.myCustomConstraint',
messages: ['app.myCustomConstraint' => $message],
strategy: $strategy
);
}
public function validate(mixed $value = null): Result
{
// it is really up to you, how you handle this
// you will just work with a normal Mighty Validator
// here we're just preparing the data to pass to the Validator
$name = '';
$data = [$name => $value];
$validations = [$name => $this->validation];
$messages = [$name => [$this->validation => $this->messages[$this->validation] ?? null]];
$labels = [$name => static::class];
// you can reuse the built-in rules or
// add you own Rule that handles your custom logic
$result = $this
->getValidator()
->addRule(
// see MAKS\Mighty\Rule for more info
(new Rule())
->setName('app.myCustomConstraint')
->setCallback(static fn ($input) => $input /* here comes your logic */)
->setParameters(['@input']) // rule callback dependencies
->setMessage('${@label} must follow my custom constraint validation.') // this is the default message
)
->setData($data)
->setValidations($validations)
->setMessages($messages)
->setLabels($labels)
->validate();
return $result[$name]; // if you implement ValidatesMany, you will just return $result
}
}
$data = array_merge(range(1, 25000), array_map('strval', range('25001', '50000')));
// Mighty Validator with XDebug disabled
[ // red to validate the array
'totalTime' => '1108.61ms', // the time g disabled
[ // ime' => '24010.60ms',
'totalTime' => '24019.93ms',
]
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.