PHP code example of bgeneto / ci4-sanitize

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

    

bgeneto / ci4-sanitize example snippets


   
   
   namespace App\Models;
   
   use CodeIgniter\Model;
   use Bgeneto\Sanitize\Traits\SanitizableTrait;
   
   class Customer extends Model
   {
       use SanitizableTrait;
   
       protected $table         = 'customers';
       protected $allowedFields = ['name', 'email', 'phone'];
   
       protected function initialize(): void
       {
           parent::initialize();
           $this->setSanitizationRules(['name' => ['uppercase'], 'email' => ['trim']]);
           $this->setSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);
       }
   }
   



namespace Bgeneto\Sanitize\Config;

use CodeIgniter\Config\BaseConfig;

class Sanitization extends BaseConfig
{
    public array $rules = [
        'UserModel' => [
            'name'  => ['trim', 'norm_spaces', 'uppercase'],
            'phone' => ['trim', 'numbers_only'],
        ],
        // Other models sanitization rules can be added here:
        'TestModel' => [
            'phrase' => ['trim', 'norm_spaces', 'capitalize'],
        ],
    ];
}

class Sanitization extends BaseConfig
{
    public array $rules = [
        'UserModel' => [
            'name'  => ['trim', 'alpha_only'],  // see new rule below
            'phone' => ['trim', 'numbers_only'],
        ],
    ];

    // new custom rule:
    public static function alpha_only(string $value): string
    {
        return preg_replace('/[^\p{L}]/u', '', $value);
    }
}

use Bgeneto\Sanitize\Sanitizer;

$rules = [
    'username' => ['trim', 'lowercase'],
    'email'    => ['trim', 'email'],
];

$sanitizer = new Sanitizer($rules);

$data = [
    'username' => '  MyUser  ',
    'email'    => '  [email protected]  ',
    'age'      => '30',
];

$sanitizedData = $sanitizer->sanitize($data);

// Output:
// [
//     'username' => 'myuser',
//     'email'    => '[email protected]',
//     'age'      => '30', // No rule for 'age', so it remains unchanged
// ]

$sanitizer->addRules(['username' => ['alphanumeric']]);
$sanitizedData = $sanitizer->sanitize($data);

$sanitizer = new Sanitizer(['name' => ['trim']]);
$data = ['name' => '  John Doe  ', 'email' => ' [email protected] '];
$lateRules = ['email' => ['trim', 'email']];
$sanitizedData = $sanitizer->sanitize($data, $lateRules);
// Result: ['name' => 'John Doe', 'email' => '[email protected]']

use Bgeneto\Sanitize\Sanitizer;

// Define a custom rule to append text to a string
Sanitizer::registerRule('append_text', function ($value, $params = []) {
    $suffix = $params[0] ?? '_appended';
    return $value . $suffix;
});

// Apply the custom rule
$sanitized = Sanitizer::applyRule('My String', 'append_text:!!!'); // $sanitized = "My String!!!"

// Another custom rule example: convert a string to a slug
Sanitizer::registerRule('my_slug', function ($value) {
    $value = \transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $value);
    $value = \preg_replace('/[^a-z0-9]+/u', '-', $value);
    return \trim($value, '-');
});

$slug = Sanitizer::applyRule('My Awesome Title', 'my_slug'); // $slug = "my-awesome-title"

Sanitizer::resetRules(); // Removes all custom rules

use Bgeneto\Sanitize\Sanitizer;

$trimmed = Sanitizer::applyRule('  Hello World  ', 'trim'); // $trimmed = "Hello World"
$lowercase = Sanitizer::applyRule('Hello World', 'lowercase'); // $lowercase = "hello world"
$numbers = Sanitizer::applyRule('Phone: 123-456-7890', 'numbers_only'); // $numbers = "1234567890"
$stripped = Sanitizer::applyRule('<p>Hello</p><a>World</a>', 'strip_tags_allowed:<p>'); // $stripped = "<p>Hello</p>World"




namespace App\Models;

use CodeIgniter\Model;
use Bgeneto\Sanitize\Traits\SanitizableTrait;

class UserModel extends Model
{
    use SanitizableTrait;

    protected $table         = 'users';
    protected $allowedFields = ['name', 'email', 'phone'];
    protected function initialize(): void
    {
        parent::initialize();
        // We just need to configure the desired sanitization callbacks 
        $this->setSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);
    }
}


$model->setSanitizationRules(['name' => ['capitalize']]);

$rules = $userModel->getSanitizationRules(); // Get all rules
$nameRules = $userModel->getSanitizationRules('name'); // Get rules for the 'name' field

$data = [
    'name' => '  john doe  ',
    'email' => '  [email protected]  ',
];

$sanitizedData = $userModel->sanitizeData($data);
bash
php spark sanitize:publish