kariricode / sanitizer
Composable, rule-based data sanitization engine for PHP 8.4+ — 33 rules, #[Sanitize] attributes, XSS prevention, powered by kariricode/property-inspector. ARFA 1.3.
Fund package maintenance!
Requires
- php: ^8.4
- kariricode/property-inspector: ^2.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-27 02:29:29 UTC
README
Composable, rule-based data sanitization engine for PHP 8.4+.
33 built-in rules · XSS prevention · #[Sanitize] attributes · zero dependencies.
Installation · Quick Start · Attribute API · All 33 Rules · CI Integration · Architecture
The Problem
User input arrives as raw strings — untrusted, inconsistent, and potentially malicious:
// Raw input from request — dangers everywhere $email = $_POST['email']; // " ALICE@EXAMPLE.COM " — extra spaces, wrong case $bio = $_POST['bio']; // "<script>alert('XSS')</script>Hello!" $phone = $_POST['phone']; // "(11) 9 9999.9999" — inconsistent format $username = $_POST['username']; // "Alice O'Connor; DROP TABLE users; --"
The Solution
use KaririCode\Sanitizer\Provider\SanitizerServiceProvider; $engine = (new SanitizerServiceProvider())->createEngine(); $result = $engine->sanitize( data: ['email' => ' ALICE@EXAMPLE.COM ', 'bio' => '<script>alert(1)</script>Hello!'], rules: [ 'email' => ['trim', 'lowercase'], 'bio' => ['html.encode', ['truncate', ['max' => 200, 'suffix' => '…']]], ], ); // $result->get('email') === "alice@example.com" // $result->get('bio') === "<script>alert(1)</script>Hello!"
Features
- ✅ 33 built-in rules across 7 categories (String, HTML, Numeric, Date, Filter, Type, Brazilian)
- ✅ XSS prevention —
html.encode,strip_tags,remove_scriptsbuilt-in - ✅ Attribute-driven API — annotate DTOs with
#[Sanitize], zero boilerplate - ✅ Dot-notation paths — sanitize nested fields like
address.city - ✅ Zero external dependencies — only
kariricode/property-inspectorfor reflection - ✅ PHPStan Level 9 + Psalm Level 1 — full static-analysis compliance
- ✅ 100% test coverage — 175 tests, 100% Classes/Methods/Lines
- ✅ ARFA 1.3 compliant —
final readonlydomain classes, immutable context
Requirements
| Requirement | Version |
|---|---|
| PHP | 8.4+ |
| Composer | 2.x |
| kariricode/property-inspector | ^2.0 |
Installation
composer require kariricode/sanitizer
Quick Start
1. Engine API
use KaririCode\Sanitizer\Provider\SanitizerServiceProvider; $engine = (new SanitizerServiceProvider())->createEngine(); $result = $engine->sanitize( data: ['name' => ' WALMIR SILVA ', 'bio' => '<b>Developer</b> & creator'], rules: ['name' => ['trim', 'capitalize'], 'bio' => ['html.decode', 'trim']], ); echo $result->get('name'); // "Walmir Silva" echo $result->get('bio'); // "Developer & creator"
2. Attribute API (DTO-driven)
use KaririCode\Sanitizer\Attribute\Sanitize; use KaririCode\Sanitizer\Provider\SanitizerServiceProvider; final class UserRegistrationInput { public function __construct( #[Sanitize('trim', 'lowercase')] public string $email, #[Sanitize('trim', 'html.encode')] public string $bio, #[Sanitize('trim', 'remove_scripts')] public string $username, ) {} } $provider = new SanitizerServiceProvider(); $sanitizer = $provider->createAttributeSanitizer($provider->createConfiguration()); $input = new UserRegistrationInput(' ALICE@EXAMPLE.COM ', '<b>Hi!</b>', '<script>evil</script>Alice'); $result = $sanitizer->sanitize($input); // ['email' => 'alice@example.com', 'bio' => '<b>Hi!</b>', 'username' => 'Alice']
Real-World Use Cases
Use Case 1 — User Registration Form
final class RegistrationInput { #[Sanitize('trim', 'lowercase')] public string $email; #[Sanitize('trim', ['min_length' => ['min' => 8]], 'capitalize')] public string $name; #[Sanitize('trim', 'html.encode', ['truncate', ['max' => 500]])] public string $bio; #[Sanitize('remove_non_numeric')] // strips dashes, spaces, brackets public string $phone; }
Use Case 2 — API Payload Normalisation (Nested Fields)
$engine->sanitize( data: ['user' => ['name' => ' Alice ', 'email' => 'ALICE@EXAMPLE.COM']], rules: [ 'user.name' => ['trim', 'capitalize'], 'user.email' => ['trim', 'lowercase'], ], );
Use Case 3 — CMS Rich-Text Sanitization
$engine->sanitize( data: ['content' => $htmlFromEditor], rules: [ 'content' => [ ['allowed_tags', ['tags' => '<p><br><strong><em><ul><ol><li>']], 'remove_scripts', 'normalize_whitespace', ], ], );
Use Case 4 — Brazilian Document Formatting
$engine->sanitize( data: ['cpf' => '123.456.789-01', 'cnpj' => '12.345.678/0001-99'], rules: ['cpf' => ['remove_non_numeric'], 'cnpj' => ['remove_non_numeric']], ); // Strips formatting → pure digits for database storage
All 33 Rules
String
| Alias | Description |
|---|---|
trim |
Remove surrounding whitespace |
lowercase / uppercase |
Case normalisation |
capitalize |
Capitalise first letter of each word |
slug |
Convert to URL-safe slug |
remove_whitespace |
Remove all whitespace |
normalize_whitespace |
Collapse multiple spaces |
remove_special_chars |
Strip non-alphanumeric |
remove_non_numeric |
Digits only |
remove_non_alpha |
Letters only |
truncate |
Truncate with suffix · max, suffix |
pad |
Pad string · length, pad_char, side |
repeat |
Repeat string · times |
reverse |
Reverse characters |
mask |
Mask characters · start, end, char |
HTML
| Alias | Description |
|---|---|
html.encode |
Encode HTML entities |
html.decode |
Decode HTML entities |
strip_tags |
Remove HTML/PHP tags |
allowed_tags |
Remove all tags except allowed · tags: string |
remove_scripts |
Remove <script> blocks |
Numeric
| Alias | Parameters | Description |
|---|---|---|
round |
precision: int |
Round to decimal places |
abs |
— | Absolute value |
clamp |
min, max |
Clamp to range |
number_format |
decimals, dec_sep, thou_sep |
Format number |
Date
| Alias | Parameters | Description |
|---|---|---|
date.format |
from, to |
Re-format date string |
date.to_iso |
— | Any date → ISO 8601 |
Filter
| Alias | Description |
|---|---|
filter.email |
Remove invalid email characters |
filter.url |
Safe URL characters only |
filter.filename |
Remove path-traversal characters |
Type
| Alias | Description |
|---|---|
to_int |
Cast to integer |
to_float |
Cast to float |
to_bool |
Cast to boolean |
to_string |
Cast to string |
Brazilian
| Alias | Description |
|---|---|
br.cpf |
Strip formatting from CPF |
br.cnpj |
Strip formatting from CNPJ |
br.cep |
Strip formatting from CEP |
CI Integration
# .github/workflows/ci.yml (excerpt) - name: Run quality pipeline run: | kcode init .kcode/phpunit.xml.dist kcode quality
| Tool | Level | Result |
|---|---|---|
php-cs-fixer |
KaririCode standard | ✅ |
phpstan |
Level 9 | ✅ |
psalm |
Level 1 | ✅ |
phpunit + pcov |
100% coverage | ✅ |
Architecture
Design Decisions
| Decision | Rationale | ADR |
|---|---|---|
| Alias-based in-memory registry | Decouples engine from rules; custom rules register via alias | ADR-001 |
PropertyInspector for #[Sanitize] |
Reflection caching; zero manual ReflectionClass loops | ADR-002 |
SanitizationContext immutability |
final readonly + builder pattern; prevents cross-field pollution |
ADR-003 |
final readonly on all rules |
ARFA Principle 11 — immutable data path | SPEC-001 |
Project Stats
| Metric | Value |
|---|---|
| Source files | 40+ |
| Rule classes | 33 |
| External dependencies | 1 (kariricode/property-inspector) |
| PHPUnit tests | 175 |
| Line coverage | 100% |
| PHPStan level | 9 (0 errors) |
| Psalm level | 1 (0 errors) |
Ecosystem Integration
| Library | Integration |
|---|---|
| kariricode/validator | Sanitize input before validation in DPO pipeline |
| kariricode/transformer | Sanitize → Transform → Persist pipeline |
| kariricode/normalizer | Sanitize, then normalize to portable format |
| kariricode/property-inspector | Reflection caching for #[Sanitize] attribute scanning |
| kariricode/devkit | kcode quality CI pipeline, PHPStan/Psalm/cs-fixer unified runner |
Development
This package keeps no QA tools in require-dev. KaririCode Devkit (kcode) installs PHPUnit, PHPStan, Psalm, PHP-CS-Fixer and Rector into .kcode/ (git-ignored) the first time a command needs them.
Install kcode once (PHP 8.4+):
wget https://github.com/KaririCode-PHP/devkit/releases/latest/download/kcode.phar chmod +x kcode.phar sudo mv kcode.phar /usr/local/bin/kcode
From the repository root:
composer install # runtime dependencies only kcode init # generate .kcode/ and install the toolchain (first run) kcode test # PHPUnit (--coverage, --suite=Unit, any PHPUnit option) kcode analyse # PHPStan, then Psalm kcode cs:fix # apply the code style (--check reports only) kcode quality # the CI gate: cs-fixer, PHPStan, Psalm, PHPUnit kcode quality --docker # the same gate inside the kcode PHP container
Project overrides go in devkit.php (kcode init --config writes a template); run kcode init after editing it. kcode clean --all removes .kcode/.
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feat/my-sanitizer-rule - Run:
kcode quality— all 4 tools must pass - Submit a pull request against
main
Part of the KaririCode Framework ecosystem.
Built with ❤️ by Walmir Silva · kariricode.org