PHP code example of kariricode / sanitizer

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

    

kariricode / sanitizer example snippets


// Sprinkled everywhere with no audit trail
$name  = ucwords(strtolower(trim($request->name)));
$email = strtolower(trim($request->email));
$cpf   = preg_replace('/\D/', '', $request->cpf);
$bio   = htmlspecialchars(strip_tags($request->bio));

// No record of what changed, no idempotency guarantee,
// no attribute-driven DTOs, no composition.

use KaririCode\Sanitizer\Provider\SanitizerServiceProvider;

$engine = (new SanitizerServiceProvider())->createEngine();

$result = $engine->sanitize(
    data: [
        'name'  => '  walmir  SILVA  ',
        'email' => '  [email protected]  ',
        'cpf'   => '52998224725',
        'bio'   => '<script>alert("xss")</script><b>Bold</b>',
    ],
    fieldRules: [
        'name'  => ['trim', 'normalize_whitespace', 'capitalize'],
        'email' => ['trim', 'lower_case', 'email_filter'],
        'cpf'   => ['format_cpf'],
        'bio'   => ['strip_tags', 'html_encode'],
    ],
);

echo $result->get('name');  // "Walmir Silva"
echo $result->get('email'); // "[email protected]"
echo $result->get('cpf');   // "529.982.247-25"
echo $result->get('bio');   // "&lt;script&gt;...Bold"



aririCode\Sanitizer\Provider\SanitizerServiceProvider;

$engine = (new SanitizerServiceProvider())->createEngine();

$result = $engine->sanitize(
    data: ['name' => '  walmir  SILVA  ', 'email' => '  [email protected]  '],
    fieldRules: [
        'name'  => ['trim', 'normalize_whitespace', 'capitalize'],
        'email' => ['trim', 'lower_case', 'email_filter'],
    ],
);

echo $result->get('name');  // "Walmir Silva"
echo $result->get('email'); // "[email protected]"

use KaririCode\Sanitizer\Attribute\Sanitize;
use KaririCode\Sanitizer\Provider\SanitizerServiceProvider;

final class CreateUserRequest
{
    #[Sanitize('trim', 'lower_case', 'email_filter')]
    public string $email = '  [email protected]  ';

    #[Sanitize('trim', 'capitalize')]
    public string $name = '  walmir silva  ';

    #[Sanitize('format_cpf')]
    public string $cpf = '52998224725';

    #[Sanitize(['truncate', ['max' => 200, 'suffix' => '…']])]
    public string $bio = '';
}

$sanitizer = (new SanitizerServiceProvider())->createAttributeSanitizer();
$dto       = new CreateUserRequest();
$sanitizer->sanitize($dto);

// $dto->email === '[email protected]'
// $dto->name  === 'Walmir Silva'
// $dto->cpf   === '529.982.247-25'

$result = $engine->sanitize(
    ['name' => '  Walmir  '],
    ['name' => ['trim', 'upper_case']],
);

$result->wasModified();        // true
$result->modifiedFields();     // ['name']
$result->modificationCount();  // 2

foreach ($result->modificationsFor('name') as $mod) {
    echo "{$mod->ruleName}: '{$mod->before}' → '{$mod->after}'\n";
}
// trim: '  Walmir  ' → 'Walmir'
// upper_case: 'Walmir' → 'WALMIR'

$result = $engine->sanitize(
    ['input' => '<script>alert("xss")</script><b>Bold</b>'],
    ['input' => ['strip_tags', 'html_encode']],
);
// Result: "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Bold"
// strip_tags alone: 'alert("xss")Bold'
// html_purify (strip + entity decode + trim): 'Bold'

$result = $engine->sanitize(
    ['cpf' => '52998224725', 'cnpj' => '11222333000181', 'cep' => '63100000'],
    ['cpf' => ['format_cpf'], 'cnpj' => ['format_cnpj'], 'cep' => ['format_cep']],
);
// cpf:  "529.982.247-25"
// cnpj: "11.222.333/0001-81"
// cep:  "63100-000"

// truncate — max chars + suffix
$engine->sanitize(['bio' => $bio], ['bio' => [['truncate', ['max' => 200, 'suffix' => '…']]]]);

// pad — length, pad char, side ('left'|'right'|'both')
$engine->sanitize(['id' => '7'], ['id' => [['pad', ['length' => 5, 'pad' => '0', 'side' => 'left']]]]);
// → "00007"

// round — precision and mode ('round'|'ceil'|'floor')
$engine->sanitize(['price' => 9.9], ['price' => [['round', ['precision' => 2]]]]);

// clamp — min and max bounds
$engine->sanitize(['age' => 150], ['age' => [['clamp', ['min' => 0, 'max' => 120]]]]);

// normalize_date — from/to format
$engine->sanitize(['dob' => '25/12/1990'], ['dob' => [['normalize_date', ['from' => 'd/m/Y', 'to' => 'Y-m-d']]]]);
// → "1990-12-25"

use KaririCode\Sanitizer\Contract\SanitizationRule;
use KaririCode\Sanitizer\Contract\SanitizationContext;

final class PhoneRule implements SanitizationRule
{
    public function sanitize(mixed $value, SanitizationContext $context): mixed
    {
        if (!is_string($value)) {
            return $value;   // ARFA passthrough — do not coerce
        }
        return preg_replace('/\D/', '', $value) ?? $value;
    }

    #[\Override]
    public function getName(): string
    {
        return 'phone';
    }
}

// Register and use
$registry = (new SanitizerServiceProvider())->createRegistry();
$registry->register('phone', new PhoneRule());

$engine = new SanitizerEngine($registry);
$result = $engine->sanitize(['phone' => '(85) 99999-9999'], ['phone' => ['phone']]);
// → "85999999999"