PHP code example of infocyph / reqshield

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

    

infocyph / reqshield example snippets


$validator = Validator::make([
    'email' => 'tSanitizers([
    'email' => ['trim', 'lowercase'],
])->setCasts([
    'age' => 'integer',
]);

$result = $validator->validate($data);

if ($result->passes()) {
    $clean = $result->typed();
    // All good!
}

use Infocyph\ReqShield\Validator;

$validator = Validator::make([
    'email' => [
        'rules' => ' => ''email.) {
    $validated = $result->typed();
    // Process your data...
} else {
    $errors = $result->errors();
    $failures = $result->failures();
    // Handle validation errors...
}

use Infocyph\ReqShield\Sanitizer;

$clean = [
    'email' => Sanitizer::email($input['email']),           // '[email protected]'
    'username' => Sanitizer::alphaDash($input['username']), // 'john_doe'
    'age' => Sanitizer::integer($input['age']),             // 25
    'bio' => Sanitizer::string($input['bio']),              // Strips HTML tags
];

$result = $validator->validate($clean);

$validator = Validator::make([
    'email' => '->setSanitizers([
    'email' => ['trim', 'lowercase'],
    'contacts.*.email' => ['trim', 'lowercase'],
]);

$clean = sanitize('  [email protected]  ', 'email');           // '[email protected]'
$clean = sanitize('<b>TEXT</b>', ['string', 'lowercase']); // 'text'

$validator = Validator::make([
    'upload' => ' 'upload_id' => '

$result = Validator::fromArray($rules, $data);
$result = Validator::fromQuery($rules, $_GET);
$result = Validator::fromBody($rules, $body);
$result = Validator::fromFiles($rules, $_FILES);

$result = Validator::fromServerRequest($rules, $request);

$validator = Validator::make($rules)
    ->strict();            // same as allowUnknown(false)

$validator = Validator::make($rules)
    ->stripUnknown();      // remove unknown fields instead of failing

'status' => '

'status' => [
    'rules' => 'erStatus::class,
]

use Infocyph\ReqShield\Support\ValidationContext;

$validator->after(function (ValidationContext $ctx): void {
    if ((string) $ctx->get('start_date') > (string) $ctx->get('end_date')) {
        $ctx->addError('end_date', 'End date must be after start date.');
    }
});

$result->toProblemJson();
$result->toJsonApiErrors();
$result->toApiErrors();
$result->toFlatErrors();

$input = $result->input();
$input->string('email');
$input->int('age');
$input->only(['email', 'age']);

$validator = Validator::make([
    'user.email' => 'ile.age' => 'dation();

$data = [
    'user' => [
        'email' => '[email protected]',
        'name' => 'John Doe',
        'profile' => [
            'age' => 25,
            'bio' => 'Software developer',
        ],
    ],
];

$result = $validator->validate($data);

$validator->setFieldAliases([
    'user_email' => 'Email Address',
    'contacts.*.email' => 'Contact Email',
]);

$validator
    ->setCustomMessages([
        'email.
        'contacts.*.email.email' => 'Each :field must be valid.',
    ])
    ->addLocalePack('es', [
        '

use Infocyph\ReqShield\Exceptions\ValidationException;

$validator = Validator::make($rules)->throwOnFailure();

try {
    $result = $validator->validate($data);
    $validated = $result->validated();
} catch (ValidationException $e) {
    echo $e->getMessage();              // "Validation failed"
    print_r($e->getErrors());           // All errors
    echo $e->getErrorCount();           // Number of failed fields
    echo $e->getFirstFieldError('email'); // First error for specific field
    echo $e->getCode();                 // 422
}

$result = $validator->validate($data);

if ($result->fails()) {
    return [
        'errors' => $result->errors(),
        'failures' => $result->failures(), // field, rule, message, value
    ];
}

$validator
    ->sometimes('vat', ') => ($data['country'] ?? null) === 'US',
        fn() => ['state' => '

Validator::defineFragment('address', [
    'line1' => 'lidator::make([
    'name' => '

$validator = Validator::make([
    'age' => 'asts([
    'age' => 'integer',
    'active' => 'boolean',
])->setDtoClass(App\DTO\UserInput::class);

$result = $validator->validate($data);
$typed = $result->typed();
$dto = $result->toDTO();

$compiled = Validator::compile([
    'email' => 'sult = $compiled->validate($data);

use Infocyph\ReqShield\Rules\Callback;

$validator = Validator::make([
    'code' => [
        '        message: 'The code must be an even number'
        ),
    ],
]);

use Infocyph\ReqShield\Contracts\Rule;

class StrongPassword implements Rule
{
    public function passes(mixed $value, string $field, array $data): bool
    {
        return strlen($value) >= 12 
            && preg_match('/[A-Z]/', $value)
            && preg_match('/[a-z]/', $value)
            && preg_match('/[0-9]/', $value)
            && preg_match('/[^A-Za-z0-9]/', $value);
    }

    public function message(string $field): string
    {
        return "The {$field} must be at least 12 characters with uppercase, lowercase, number, and special character.";
    }

    public function cost(): int { return 20; }
    public function isBatchable(): bool { return false; }
}

// Usage
$validator = Validator::make([
    'password' => ['

use Infocyph\ReqShield\Validator;
use Infocyph\ReqShield\Contracts\DatabaseProvider;

// Implement your database provider
class MyDatabaseProvider implements DatabaseProvider
{
    // Implement 

$jsonSchema = $validator->exportSchema('json_schema');
$openApiShape = $validator->exportSchema('openapi');
$introspection = $validator->exportSchema('introspection');

$validator = Validator::make($rules)
    ->setStopOnFirstError(true);

// Stops immediately when any field fails
$result = $validator->validate($data);

// 3 separate rules...
'user_id' => 'exists:users,id',
'email' => 'unique:users,email',
'category_id' => 'exists:categories,id',

// ...become just 2 queries (50x faster!)
// - One batch for exists checks
// - One batch for unique checks

'email' => ' → fails on '