---
title: "Data Processor Project"
description: "Derafu Data Processor"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-09"
last_update: "2026-11-09"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/data-processor"
---

# Derafu Data Processor



---

## Introduction

PHP library that processes data in four phases: casting, transformation, sanitization and validation, with custom rules

# Four-Phase Data Processing Library

[![GitHub](https://img.shields.io/badge/github-derafu%2Fdata--processor-blue?logo=github)](https://github.com/derafu/data-processor)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/data-processor/main)
![CI Workflow](https://github.com/derafu/data-processor/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/data-processor)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/data-processor)
![Total Downloads](https://poser.pugx.org/derafu/data-processor/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/data-processor/d/monthly)

A PHP library designed to process data through four distinct phases: casting, transformation, sanitization and validation.

## What Makes it Different?

Unlike traditional validation libraries that focus solely on validation, Derafu Data Processor offers:

- **Clear Phase Separation**: Each processing phase (cast → transform → sanitize → validate) has its own purpose and runs in a specific order.
- **Independent Transformations**: A dedicated transformation layer for complex data conversions, separate from basic type casting.
- **Type-Safe Operations**: Strong typing and clear error handling in each phase.
- **Extensible Rule System**: Each type of rule (caster, transformer, sanitizer, validator) follows its own interface.
- **Minimal Dependencies**: `intl` extension for specific format rules, `Carbon` for dates, and `derafu/translation` for translatable error messages (see [Translations](translations)).

## Features

- 🎯 **Type-Safe Casting**: Convert between data types safely.
  - Basic types (string, int, float, bool), strict: a value that is not clearly a boolean or an integer is an error, it is not guessed.
  - Date and time handling, with absolute ISO 8601 dates (a relative text like `tomorrow` is an error).

- 🔄 **Data Transformations**: Complex data conversions.
  - Base64 encoding/decoding.
  - JSON processing.
  - Slug generation.
  - Character transliteration.

- 🧹 **Rich Sanitization Rules**: Clean and normalize input data.
  - String sanitization (trim, strip_tags, substring, etc.).
  - Regex-based cleaning (regex_remove, regex_keep).
  - HTML entity handling (htmlspecialchars, htmlentities, etc.).
  - Character set manipulation (remove_non_printable, remove_chars, etc.).

- ✅ **Comprehensive Validation**: Various validation rules.
  - String validations (required, min_length, max_length, etc.).
  - Number validations (range, gte, lte, etc.).
  - Date validations (after, before, between, etc.).
  - Format validations (email, URL, UUID, IBAN, hostname, host, etc.).
  - Values of HTML inputs (color, month, week, time, datetime_local).
  - File validations (file, image, mimetype).
  - Array validations (min_items, max_items, contains, allowed_keys, dependent_required, unique, unique_loose, etc.).

- 🫙 **Optional Fields**: A `null`, `&#039;&#039;` or `[]` value is `null` without running the rules, unless the field is `required`.

## Installation

```bash
composer require derafu/data-processor
```

## Basic Usage

```php
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\Registrar\DefaultRuleRegistrar;
use Derafu\DataProcessor\RuleParser;
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\RuleResolver;

$registry = new RuleRegistry();
(new DefaultRuleRegistrar())-&gt;register($registry);
$processor = new Processor(new RuleResolver($registry), new RuleParser());

// Simple validation.
$result = $processor-&gt;process(&#039;test@example.com&#039;, [
    &#039;validate&#039; =&gt; [&#039;email&#039;],
]);

// Multi-phase processing.
$result = $processor-&gt;process(&#039; TEST@EXAMPLE.COM &#039;, [
    &#039;transform&#039; =&gt; [&#039;lowercase&#039;],
    &#039;sanitize&#039; =&gt; [&#039;trim&#039;],
    &#039;validate&#039; =&gt; [&#039;email&#039;, &#039;max_length:255&#039;],
]);

// Array validation.
$result = $processor-&gt;process([1, 2, 2, 3], [
    &#039;validate&#039; =&gt; [&#039;unique&#039;, &#039;max_items:5&#039;],
]);

// File validation.
$result = $processor-&gt;process($_FILES[&#039;upload&#039;], [
    &#039;validate&#039; =&gt; [&#039;file:2M&#039;, &#039;mimetype:application/pdf,image/*&#039;]
]);
```

## Dependency Injection

Applications using Symfony DependencyInjection can import the package configuration:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }
```

Inject `Derafu\DataProcessor\Contract\ProcessorInterface` into your application services.
The configured processor uses the container&#039;s `RuleResolverInterface` and
`RuleParserInterface`. The resolver uses the same `RuleRegistryInterface` registered
in the container.

The registry is initialized by `RuleRegistrarInterface`, implemented by
`CompositeRuleRegistrar`. It collects services tagged with
`derafu_data_processor.rule_registrar`. `DefaultRuleRegistrar` has priority `1000`;
additional registrars normally use priority `0` and run afterward, allowing them
to add rules or replace existing names. Higher priorities run first; among equal
priorities, registration order is preserved. See [Custom Registrar](custom-registrar)
and [Custom Parser](custom-parser).

The YAML supplies the processor and its rules. Configuring an application translator
is a separate choice; see [Translations](translations).




---

## Rules Reference

Rules Reference

# Rules Reference

## Cast Rules

| Rule | Description | Example |
|------|-------------|---------|
| `boolean`, `bool` | Convert value to boolean. Only clear values are accepted: `true`, `1`, `yes`, `on` and `false`, `0`, `no`, `off`, `&#039;&#039;`, `null` (text without distinguishing case); any other value is an error | `&#039;cast&#039; =&gt; &#039;boolean&#039;` |
| `date` | Convert an absolute ISO 8601 date to a Carbon date (see [Absolute dates](#absolute-dates)) | `&#039;cast&#039; =&gt; &#039;date&#039;` |
| `datetime` | Convert an absolute ISO 8601 date and time to a Carbon datetime (see [Absolute dates](#absolute-dates)) | `&#039;cast&#039; =&gt; &#039;datetime&#039;` |
| `float`, `decimal` | Convert value to float. A float does not keep trailing zeros (`&#039;10.50&#039;` is `10.5`), so validate its decimals with `decimal:0,N` (up to `N` decimals), not with `decimal:N` | `&#039;cast&#039; =&gt; &#039;float&#039;` |
| `integer`, `int` | Convert value to integer. A number with a decimal part (`&#039;1.9&#039;`) or out of range is an error, it is not truncated; `&#039;1.0&#039;` and `&#039;1e2&#039;` are `1` and `100` | `&#039;cast&#039; =&gt; &#039;integer&#039;` |
| `string`, `str` | Convert value to string | `&#039;cast&#039; =&gt; &#039;string&#039;` |
| `timestamp` | Convert value to Unix timestamp. A number is used as it is; a text must be an absolute ISO 8601 date (see [Absolute dates](#absolute-dates)) | `&#039;cast&#039; =&gt; &#039;timestamp&#039;` |

## Transform Rules

| Rule | Description | Example |
|------|-------------|---------|
| `base64_decode` | Decode base64 string | `&#039;transform&#039; =&gt; [&#039;base64_decode&#039;]` |
| `base64_encode` | Encode value to base64 | `&#039;transform&#039; =&gt; [&#039;base64_encode&#039;]` |
| `json_decode` | Decode JSON string | `&#039;transform&#039; =&gt; [&#039;json_decode&#039;]`, `&#039;transform&#039; =&gt; [&#039;json_decode:array&#039;]` |
| `json_encode` | Encode value to JSON | `&#039;transform&#039; =&gt; [&#039;json_encode&#039;]`, `&#039;transform&#039; =&gt; [&#039;json_encode:pretty&#039;]` |
| `json_to_array` | Convert JSON string to array | `&#039;transform&#039; =&gt; [&#039;json_to_array&#039;]` |
| `json_to_object` | Convert JSON string to object | `&#039;transform&#039; =&gt; [&#039;json_to_object&#039;]` |
| `round` | Round numeric value | `&#039;transform&#039; =&gt; [&#039;round:2&#039;]` |
| `lowercase`, `lower` | Convert string to lowercase | `&#039;transform&#039; =&gt; [&#039;lowercase&#039;]` |
| `slug` | Convert string to URL friendly format | `&#039;transform&#039; =&gt; [&#039;slug&#039;]` |
| `transliterate` | Convert characters to ASCII | `&#039;transform&#039; =&gt; [&#039;transliterate&#039;]` |
| `uppercase`, `upper` | Convert string to uppercase | `&#039;transform&#039; =&gt; [&#039;uppercase&#039;]` |

## Sanitize Rules

| Rule | Description | Example |
|------|-------------|---------|
| `addslashes` | Add slashes before quotes | `&#039;sanitize&#039; =&gt; [&#039;addslashes&#039;]` |
| `htmlentities` | Convert characters to HTML entities | `&#039;sanitize&#039; =&gt; [&#039;htmlentities&#039;]` |
| `htmlspecialchars` | Convert special characters to HTML entities | `&#039;sanitize&#039; =&gt; [&#039;htmlspecialchars&#039;]` |
| `regex_keep` | Keep only characters matching pattern | `&#039;sanitize&#039; =&gt; [&#039;regex_keep:/[0-9]/&#039;]` |
| `regex_remove` | Remove characters matching pattern | `&#039;sanitize&#039; =&gt; [&#039;regex_remove:/[^a-z]/&#039;]` |
| `remove_chars` | Remove specific characters | `&#039;sanitize&#039; =&gt; [&#039;remove_chars:@#$&#039;]` |
| `remove_non_printable` | Remove ASCII control characters (except tab and line feed), C1 control characters and invisible format characters (`U+200B`, `U+200E`, `U+202A` to `U+202E`, `U+2060`, `U+FEFF`, `U+00AD`). `U+200C` and `U+200D` are kept, because some scripts and emoji sequences need them | `&#039;sanitize&#039; =&gt; [&#039;remove_non_printable&#039;]` |
| `remove_prefix` | Remove string prefix | `&#039;sanitize&#039; =&gt; [&#039;remove_prefix:http&#039;]` |
| `remove_suffix` | Remove string suffix | `&#039;sanitize&#039; =&gt; [&#039;remove_suffix:.txt&#039;]` |
| `spaces` | Normalize multiple spaces to single | `&#039;sanitize&#039; =&gt; [&#039;spaces&#039;]` |
| `strip_tags` | Remove HTML and PHP tags | `&#039;sanitize&#039; =&gt; [&#039;strip_tags&#039;]`, `&#039;sanitize&#039; =&gt; [&#039;strip_tags:&lt;p&gt;&lt;br&gt;&#039;]` |
| `substring` | Extract part of string | `&#039;sanitize&#039; =&gt; [&#039;substring:5&#039;]`, `&#039;sanitize&#039; =&gt; [&#039;substring:0,10&#039;]` |
| `trim` | Remove ASCII whitespace from ends (not the no-break space `U+00A0`) | `&#039;sanitize&#039; =&gt; [&#039;trim&#039;]` |

## Validate Rules

### Array Validation

| Rule | Description | Example |
|------|-------------|---------|
| `allowed_keys` | Check that an array has only the listed keys (`additionalProperties: false` of a JSON Schema object) | `&#039;validate&#039; =&gt; [&#039;allowed_keys:name,email&#039;]` |
| `contains` | Check that the array has at least one of the listed values | `&#039;validate&#039; =&gt; [&#039;contains:terms&#039;]`, `&#039;validate&#039; =&gt; [&#039;contains:a,b&#039;]` |
| `dependent_required` | If the first key has a value, the other keys must have a value too | `&#039;validate&#039; =&gt; [&#039;dependent_required:card,address,zip&#039;]` |
| `in`, `choices` | Check if value is in list. Value and list are compared as text (`2`, `2.0` and `&#039;2&#039;` are the same choice for `in:1,2,3`); an array is valid when each element is in the list; booleans, `null` and objects are never in the list | `&#039;validate&#039; =&gt; [&#039;in:a,b,c&#039;]`, `&#039;validate&#039; =&gt; [&#039;in:1,2,3&#039;]` |
| `max_contains` | Check that the array has at most N elements that are one of the listed values | `&#039;validate&#039; =&gt; [&#039;max_contains:1,a,b&#039;]` |
| `max_items` | Check array maximum length. In an associative array, it counts the keys | `&#039;validate&#039; =&gt; [&#039;max_items:5&#039;]` |
| `min_contains` | Check that the array has at least N elements that are one of the listed values | `&#039;validate&#039; =&gt; [&#039;min_contains:2,a,b&#039;]` |
| `min_items` | Check array minimum length. In an associative array, it counts the keys | `&#039;validate&#039; =&gt; [&#039;min_items:1&#039;]` |
| `notempty` | Check if array is not empty | `&#039;validate&#039; =&gt; [&#039;notempty&#039;]` |
| `unique` | Check if array values are unique. The comparison is strict (same type and value): `[&#039;1e1&#039;, &#039;10&#039;]` and `[&#039;1&#039;, 1]` are unique | `&#039;validate&#039; =&gt; [&#039;unique&#039;]` |
| `unique_loose` | Check if array values are unique with a loose comparison (`==`): `[&#039;1e1&#039;, &#039;10&#039;]` and `[&#039;1&#039;, 1]` are duplicates | `&#039;validate&#039; =&gt; [&#039;unique_loose&#039;]` |

### Date Validation

| Rule | Description | Example |
|------|-------------|---------|
| `after` | Check if date is after another | `&#039;validate&#039; =&gt; [&#039;after:2024-01-01&#039;]` |
| `after_or_equal` | Check if date is after or equal | `&#039;validate&#039; =&gt; [&#039;after_or_equal:2024-01-01&#039;]` |
| `before` | Check if date is before another | `&#039;validate&#039; =&gt; [&#039;before:2024-12-31&#039;]` |
| `before_or_equal` | Check if date is before or equal | `&#039;validate&#039; =&gt; [&#039;before_or_equal:2024-12-31&#039;]` |
| `between` | Check if date is between two dates | `&#039;validate&#039; =&gt; [&#039;between:2024-01-01,2024-12-31&#039;]` |
| `date_equals` | Check if date equals another | `&#039;validate&#039; =&gt; [&#039;date_equals:2024-01-01&#039;]` |
| `date_format` | Check if date matches format | `&#039;validate&#039; =&gt; [&#039;date_format:Y-m-d&#039;]` |
| `datetime_local` | Check a date and time as `&lt;input type=&quot;datetime-local&quot;&gt;` sends it: `YYYY-MM-DDTHH:MM` or `YYYY-MM-DDTHH:MM:SS`, with an existing date | `&#039;validate&#039; =&gt; [&#039;datetime_local&#039;]` |
| `month` | Check a month as `&lt;input type=&quot;month&quot;&gt;` sends it: `YYYY-MM` | `&#039;validate&#039; =&gt; [&#039;month&#039;]` |
| `time` | Check a time as `&lt;input type=&quot;time&quot;&gt;` sends it: `HH:MM` or `HH:MM:SS` | `&#039;validate&#039; =&gt; [&#039;time&#039;]` |
| `week` | Check a week as `&lt;input type=&quot;week&quot;&gt;` sends it: `YYYY-Www`, with the week 53 only in the years that have it | `&#039;validate&#039; =&gt; [&#039;week&#039;]` |
| `weekday` | Check if date is weekday | `&#039;validate&#039; =&gt; [&#039;weekday&#039;]` |
| `weekend` | Check if date is weekend | `&#039;validate&#039; =&gt; [&#039;weekend&#039;]` |

### File Validation

| Rule | Description | Example |
|------|-------------|---------|
| `file` | Validate file with size limits (`max_size`, and `min_size`, 1 byte by default) | `&#039;validate&#039; =&gt; [&#039;file:2M&#039;]`, `&#039;validate&#039; =&gt; [&#039;file:max_size=2M,min_size=0&#039;]` |
| `image` | Validate image file (JPEG, PNG, GIF or WebP) with size limits (`max_size`, and `min_size`, 1 byte by default) | `&#039;validate&#039; =&gt; [&#039;image:2M&#039;]`, `&#039;validate&#039; =&gt; [&#039;image:max_size=2M,min_size=0&#039;]` |
| `mimetype` | Validate file mime type, detected from its content. A whole type allows any of its subtypes with `type/*`; any other `*` is text and never matches | `&#039;validate&#039; =&gt; [&#039;mimetype:application/pdf,image/jpeg&#039;]`, `&#039;validate&#039; =&gt; [&#039;mimetype:image/*&#039;]`, `&#039;validate&#039; =&gt; [&#039;mimetype:application/pdf,application/x-empty&#039;]` |

### Financial Validation

| Rule | Description | Example |
|------|-------------|---------|
| `bic` | Validate BIC/SWIFT code (it identifies a bank, not an account) | `&#039;validate&#039; =&gt; [&#039;bic&#039;]` |
| `card_number` | Validate credit card number | `&#039;validate&#039; =&gt; [&#039;card_number&#039;]` |
| `iban` | Validate IBAN: country, length of that country, and check digits. Spaces and lowercase are accepted. Only the countries of the SWIFT IBAN Registry have IBAN (in Latin America: Brazil, Costa Rica, Dominican Republic, Guatemala, Honduras, Nicaragua and El Salvador), any other country is an error | `&#039;validate&#039; =&gt; [&#039;iban&#039;]` |

### I18n Validation

| Rule | Description | Example |
|------|-------------|---------|
| `country` | Validate country code | `&#039;validate&#039; =&gt; [&#039;country&#039;]` |
| `currency` | Validate ISO 4217 currency code, in uppercase or lowercase. It has the codes in force, with the funds codes (`CLF`), and not the precious metals and special codes (`XAU`, `XAG`, `XDR`, `XXX`, etc.) | `&#039;validate&#039; =&gt; [&#039;currency&#039;]` |
| `language` | Validate language code (2 or 3 letters), with an optional country: `es`, `fil`, `es_CL` or `es-CL` | `&#039;validate&#039; =&gt; [&#039;language&#039;]` |
| `locale` | Validate locale code, with `_` or `-` as separator: `es_CL` or `es-CL`. The list is the one of ICU, so it depends on the version of ICU | `&#039;validate&#039; =&gt; [&#039;locale&#039;]` |
| `timezone` | Validate timezone identifier | `&#039;validate&#039; =&gt; [&#039;timezone&#039;]` |

### ID Validation

| Rule | Description | Example |
|------|-------------|---------|
| `uuid` | Validate UUID string (RFC 9562): versions 1 to 8, and the nil and max UUIDs. With a version, only that version is valid | `&#039;validate&#039; =&gt; [&#039;uuid&#039;]`, `&#039;validate&#039; =&gt; [&#039;uuid:4&#039;]` |

### Internet Validation

| Rule | Description | Example |
|------|-------------|---------|
| `email` | Validate email address. The domain can have international characters (`jose@exämple.com`); the part before `@` must be ASCII | `&#039;validate&#039; =&gt; [&#039;email&#039;]` |
| `host` | Validate a hostname or an IP address. `host:v4` and `host:v6` limit the version of the IP address; a hostname is valid anyway | `&#039;validate&#039; =&gt; [&#039;host&#039;]`, `&#039;validate&#039; =&gt; [&#039;host:v4&#039;]` |
| `hostname` | Validate hostname. The last label can not be only digits, so `1.2.3.4` and `example.123` are not hostnames (RFC 1123) | `&#039;validate&#039; =&gt; [&#039;hostname&#039;]` |
| `ip` | Validate IP address | `&#039;validate&#039; =&gt; [&#039;ip&#039;]`, `&#039;validate&#039; =&gt; [&#039;ip:v4&#039;]`, `&#039;validate&#039; =&gt; [&#039;ip:v6&#039;]` |
| `url` | Validate URL. With parameters, only those schemes are valid. A host with international characters is accepted | `&#039;validate&#039; =&gt; [&#039;url&#039;]`, `&#039;validate&#039; =&gt; [&#039;url:http,https&#039;]` |

### Numeric Validation

| Rule | Description | Example |
|------|-------------|---------|
| `decimal`, `float`, `real` | Validate decimal number with exactly `N` decimals (`decimal:2`), or between `min` and `max` decimals (`decimal:0,2`) | `&#039;validate&#039; =&gt; [&#039;decimal:2&#039;]`, `&#039;validate&#039; =&gt; [&#039;decimal:0,2&#039;]` |
| `digits_range` | Validate that the value is only digits, with a number of digits between `min` and `max` | `&#039;validate&#039; =&gt; [&#039;digits_range:3,5&#039;]` |
| `digits` | Validate that the value is only digits, with exactly that number of digits | `&#039;validate&#039; =&gt; [&#039;digits:4&#039;]` |
| `gt` | Greater than | `&#039;validate&#039; =&gt; [&#039;gt:10&#039;]` |
| `gte`, `min` | Greater than or equal | `&#039;validate&#039; =&gt; [&#039;gte:10&#039;]` |
| `integer`, `int` | Validate integer | `&#039;validate&#039; =&gt; [&#039;integer&#039;]` |
| `lt` | Less than | `&#039;validate&#039; =&gt; [&#039;lt:10&#039;]` |
| `lte`, `max` | Less than or equal | `&#039;validate&#039; =&gt; [&#039;lte:10&#039;]` |
| `multiple_of` | Check if number is multiple | `&#039;validate&#039; =&gt; [&#039;multiple_of:5&#039;]` |
| `numeric` | Validate numeric value | `&#039;validate&#039; =&gt; [&#039;numeric&#039;]` |
| `range` | Validate number in range | `&#039;validate&#039; =&gt; [&#039;range:1,100&#039;]` |

### String Validation

| Rule | Description | Example |
|------|-------------|---------|
| `alpha` | Only alphabetic characters | `&#039;validate&#039; =&gt; [&#039;alpha&#039;]` |
| `alpha_dash` | Alphanumeric with dashes/underscores | `&#039;validate&#039; =&gt; [&#039;alpha_dash&#039;]` |
| `alpha_num` | Only alphanumeric characters | `&#039;validate&#039; =&gt; [&#039;alpha_num&#039;]` |
| `base64` | Validate base64 string | `&#039;validate&#039; =&gt; [&#039;base64&#039;]` |
| `color` | Check a color as `&lt;input type=&quot;color&quot;&gt;` sends it: `#rrggbb`, in uppercase or lowercase (`#fff` and `red` are not valid) | `&#039;validate&#039; =&gt; [&#039;color&#039;]` |
| `ends_with` | String ends with value | `&#039;validate&#039; =&gt; [&#039;ends_with:Test&#039;]` |
| `json` | Validate JSON string | `&#039;validate&#039; =&gt; [&#039;json&#039;]` |
| `length` | Exact string length | `&#039;validate&#039; =&gt; [&#039;length:10&#039;]` |
| `max_length` | Maximum string length | `&#039;validate&#039; =&gt; [&#039;max_length:255&#039;]` |
| `min_length` | Minimum string length | `&#039;validate&#039; =&gt; [&#039;min_length:3&#039;]` |
| `not_regex` | Not match regular expression | `&#039;validate&#039; =&gt; [&#039;not_regex:/[0-9]/&#039;]` |
| `no_whitespace` | No whitespace in string | `&#039;validate&#039; =&gt; [&#039;no_whitespace&#039;]` |
| `regex` | Match regular expression | `&#039;validate&#039; =&gt; [&#039;regex:/^[A-Z]+$/&#039;]` |
| `required` | Value is required (`null`, `&#039;&#039;` and `[]` fail) | `&#039;validate&#039; =&gt; [&#039;required&#039;]` |
| `slug` | Validate URL friendly string | `&#039;validate&#039; =&gt; [&#039;slug&#039;]` |
| `starts_with` | String starts with value | `&#039;validate&#039; =&gt; [&#039;starts_with:Test&#039;]` |

## Notes

### Rule parameters

The parameters of a rule go after `:`, separated by commas. A comma that is part of a parameter is written as `\,`: `&#039;in:a\,b,c&#039;` has two choices, `a,b` and `c`. A parameter that is not valid is an error, it is not replaced by another value (`&#039;uuid:9&#039;` fails with `Invalid parameter: 9`).

The rules that take a literal (`regex`, `not_regex`, `starts_with`, `ends_with`, `date_format`, `after`, `before`, `trim`, `remove_chars`, `strip_tags`, `transliterate`, etc.) receive all the text after `:` as one parameter, and `\,` has no special meaning for them.

### Empty values

A value that is `null`, `&#039;&#039;` or `[]` has nothing to cast, transform or sanitize. If the rules do not have `required`, the result is `null` and the validators do not run, so an optional field sent empty is valid. If the rules have `required`, the validators run and the value fails with `Field is required.`

### Absolute dates

The date validators (`after`, `before`, `between`, `date_equals`, `weekday`, `weekend`, etc.) and the casters `date`, `datetime` and `timestamp` accept as text only an absolute date in ISO 8601: `YYYY-MM-DD`, or with time, `YYYY-MM-DDTHH:MM[:SS[.fraction]]` (a space can replace the `T`), with `Z` or an offset (`+03:00`) at the end. The date and the time must exist. Date objects are accepted too.

A relative text (`tomorrow`, `+1 week`, `now`) or another format (`01/02/2024`, which can be read as January 2 or February 1) is an error, because its value depends on the clock of the server or on how it is read. `date_format` validates a text in another format; to convert it, read it with your own code before processing. The parameter that a rule compares with (`after:tomorrow`) can still be relative.

### Arrays and objects

The array validators also work with an associative array (an object): `min_items` and `max_items` count its keys.

`contains`, `min_contains` and `max_contains` compare the elements with the listed values as text, like `in`: `2`, `2.0` and `&#039;2&#039;` are the same value. Booleans, `null` and arrays are never equal to a value. In `min_contains` and `max_contains` the first parameter is the number `N`, and the rest are the values: `&#039;min_contains:2,a,b&#039;` needs at least two elements that are `a` or `b`. `N` must be an integer of 0 or more.

`allowed_keys` compares the keys of the array as text. `&#039;allowed_keys:a,b&#039;` fails with `Properties not allowed: c.` for `[&#039;a&#039; =&gt; 1, &#039;c&#039; =&gt; 2]`.

In `dependent_required` the first parameter is the key that triggers the rule, and the rest are the keys that become required. A key has a value when it exists and is not `null`, `&#039;&#039;` or `[]` (`false` and `0` are values). If the first key has no value, the rule passes. `&#039;dependent_required:card,address&#039;` fails with `Properties required when card is present: address.` for `[&#039;card&#039; =&gt; &#039;4111&#039;, &#039;address&#039; =&gt; &#039;&#039;]`.

A value that is not an array fails with `Value must be an array.`




---

## Custom Registries

Creating Custom Registries

# Creating Custom Registries

You can create your own rule registry to customize which rules are available:

```php
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\RuleResolver;

// Create a custom registry.
$registry = new RuleRegistry();

// Register only the rules you need.
$registry
    -&gt;addTransformerRule(&#039;base64_encode&#039;, Base64EncodeRule::class)
    -&gt;addSanitizerRule(&#039;trim&#039;, TrimRule::class)
    -&gt;addCasterRule(&#039;integer&#039;, IntegerRule::class)
    -&gt;addValidatorRule(&#039;email&#039;, EmailRule::class);

// Create resolver, parser and processor with your registry.
$resolver = new RuleResolver($registry);
$parser = new RuleParser();
$processor = new Processor($resolver, $parser);
```




---

## Custom Rules

Creating Custom Rules

# Creating Custom Rules

## Custom Cast Rule

```php
use Derafu\DataProcessor\Contract\CasterRuleInterface;

final class CustomCastRule implements CasterRuleInterface
{
    public function cast(mixed $value, array $parameters = []): mixed
    {
        // Your casting logic here.
    }
}

// Register the rule.
$registry-&gt;addCasterRule(&#039;custom_cast&#039;, CustomCastRule::class);
```

## Custom Transform Rule

```php
use Derafu\DataProcessor\Contract\TransformerRuleInterface;

final class CustomTransformRule implements TransformerRuleInterface
{
    public function transform(mixed $value, array $parameters = []): mixed
    {
        // Your transformation logic here.
    }
}

// Register the rule.
$registry-&gt;addTransformerRule(&#039;custom_transform&#039;, CustomTransformRule::class);
```

## Custom Sanitizer Rule

```php
use Derafu\DataProcessor\Contract\SanitizerRuleInterface;

final class CustomSanitizerRule implements SanitizerRuleInterface
{
    public function sanitize(mixed $value, array $parameters = []): mixed
    {
        // Your sanitization logic here.
    }
}

// Register the rule.
$registry-&gt;addSanitizerRule(&#039;custom_sanitize&#039;, CustomSanitizerRule::class);
```

## Custom Validator Rule

```php
use Derafu\DataProcessor\Contract\ValidatorRuleInterface;

final class CustomValidatorRule implements ValidatorRuleInterface
{
    public function validate(mixed $value, array $parameters = []): void
    {
        // Your validation logic here.
    }
}

// Register the rule.
$registry-&gt;addValidatorRule(&#039;custom_validate&#039;, CustomValidatorRule::class);
```

## Using Custom Rules

Once registered, you can use your custom rules just like built-in ones:

```php
$processor-&gt;process(&#039;field&#039;, $value, [
    &#039;cast&#039; =&gt; &#039;custom_cast&#039;,
    &#039;transform&#039; =&gt; [&#039;custom_transform&#039;],
    &#039;sanitize&#039; =&gt; [&#039;custom_sanitize&#039;],
    &#039;validate&#039; =&gt; [&#039;custom_validate&#039;],
]);
```




---

## Custom Registrar

Creating a Custom Rule Registrar

# Creating a Custom Rule Registrar

A registrar groups rule registrations. It can add caster, transformer, sanitizer
and validator rules, including application-specific names for existing rule classes.
For example:

```php
namespace App\DataProcessor;

use Derafu\DataProcessor\Contract\RuleRegistrarInterface;
use Derafu\DataProcessor\Contract\RuleRegistryInterface;
use Derafu\DataProcessor\Rule\Transformer\String\UppercaseRule;
use Derafu\DataProcessor\Rule\Validator\String\MinLengthRule;

final class CustomRuleRegistrar implements RuleRegistrarInterface
{
    public function register(RuleRegistryInterface $registry): void
    {
        $registry-&gt;addTransformerRule(&#039;capital_letters&#039;, UppercaseRule::class);
        $registry-&gt;addValidatorRule(&#039;display_name&#039;, MinLengthRule::class);
    }
}
```

## Dependency Injection

Import the package configuration and tag the registrar. Each member of the
collection has its own service ID; the composite remains registered under
`RuleRegistrarInterface`.

```yaml
imports:
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }

services:
    App\DataProcessor\CustomRuleRegistrar:
        tags: [&#039;derafu_data_processor.rule_registrar&#039;]
```

The processor injected through `ProcessorInterface` can use both default and
additional rules:

```php
$result = $processor-&gt;process(&#039;alice&#039;, [
    &#039;transform&#039; =&gt; [&#039;capital_letters&#039;],
    &#039;validate&#039; =&gt; [&#039;required&#039;, &#039;display_name:3&#039;],
]);
// &#039;ALICE&#039;
```

`DefaultRuleRegistrar` has tag priority `1000`; additional registrars use priority
`0` unless configured otherwise. Higher priorities run first. A later registration
of the same name in the same category replaces the earlier rule. This lets a tagged
registrar override a default without discarding unrelated defaults.

## Explicit Construction

Without a container, initialize a registry with the registrars you choose:

```php
use App\DataProcessor\CustomRuleRegistrar;
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\Registrar\CompositeRuleRegistrar;
use Derafu\DataProcessor\Registrar\DefaultRuleRegistrar;
use Derafu\DataProcessor\RuleParser;
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\RuleResolver;

$registry = new RuleRegistry();
(new CompositeRuleRegistrar([
    new DefaultRuleRegistrar(),
    new CustomRuleRegistrar(),
]))-&gt;register($registry);

$processor = new Processor(new RuleResolver($registry), new RuleParser());
```

To use only custom rules, omit `DefaultRuleRegistrar` from that explicit list.
The package YAML includes defaults automatically.




---

## Custom Parser

Creating a Custom Rule Parser

# Creating a Custom Rule Parser

Implement `RuleParserInterface` to support application-specific rule syntax.
This parser adds a `contact_email` shorthand and delegates other strings and arrays
to the built-in parser:

```php
namespace App\DataProcessor;

use Derafu\DataProcessor\Contract\RuleParserInterface;
use Derafu\DataProcessor\RuleParser;

final class ContactRuleParser implements RuleParserInterface
{
    public function parse(string|array $rules): array
    {
        return (new RuleParser())-&gt;parse(
            $rules === &#039;contact_email&#039;
                ? &#039;t(lowercase) s(trim) required|email&#039;
                : $rules
        );
    }
}
```

## Dependency Injection

Import the package YAML, then replace the parser under its interface ID:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }

services:
    Derafu\DataProcessor\Contract\RuleParserInterface:
        class: App\DataProcessor\ContactRuleParser
```

The configured `ProcessorInterface` receives this parser. In a service that receives
that processor, the shorthand works directly:

```php
$result = $processor-&gt;process(&#039; TEST@EXAMPLE.COM &#039;, &#039;contact_email&#039;);
// &#039;test@example.com&#039;
```

The parser returns categories (`cast`, `transform`, `sanitize`, `validate`) with the
same structure expected by the processor. It changes how rules are expressed, not
the order of the processing phases.

## Explicit Construction

Without a container, supply the parser through the processor constructor:

```php
use App\DataProcessor\ContactRuleParser;
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\Registrar\DefaultRuleRegistrar;
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\RuleResolver;

$registry = new RuleRegistry();
(new DefaultRuleRegistrar())-&gt;register($registry);
$processor = new Processor(new RuleResolver($registry), new ContactRuleParser());

$result = $processor-&gt;process(&#039; TEST@EXAMPLE.COM &#039;, &#039;contact_email&#039;);
// &#039;test@example.com&#039;
```




---

## Translations

Translations

# Translations

`derafu/data-processor`&#039;s exceptions can be translated. This page explains
what&#039;s translatable, what ships out of the box, and how to activate it in
your application.

## What&#039;s Translatable

Four exception classes implement
`Derafu\Translation\Contract\TranslatableInterface` (via
`TranslatableExceptionTrait`, from
[`derafu/translation`](https://www.derafu.dev/docs/core/translation)):

- `Derafu\DataProcessor\Exception\ValidationException`
- `Derafu\DataProcessor\Exception\SanitizationException`
- `Derafu\DataProcessor\Exception\TransformationException`
- `Derafu\DataProcessor\Exception\CastingException`

`Derafu\DataProcessor\Exception\RuleNotFoundException` is **not**
translatable on purpose — it signals a misconfigured rule name (a
programming/configuration error), not something an end user should ever
see.

All four use the `errors` domain (`TranslatableExceptionTrait`&#039;s default).
Every message thrown by a built-in rule is written in ICU MessageFormat
syntax and uses the literal English text as its translation id — for
example, `&#039;Value must be greater than {value}.&#039;` — following the same
convention documented in
[derafu/translation&#039;s Exceptions guide](https://www.derafu.dev/docs/core/translation).

Without any translator configured, `getMessage()` already returns the
fully formatted English text — this library works exactly as before,
whether or not you set up translation at all:

```php
use Derafu\DataProcessor\Exception\ValidationException;

$e = new ValidationException([&#039;Array must not contain more than {max} items.&#039;, &#039;max&#039; =&gt; 5]);

echo $e-&gt;getMessage();
// &quot;Array must not contain more than 5 items.&quot;
```

## What Ships

`derafu/data-processor` includes:

- `resources/translations/errors+intl-icu.es.php` — a Spanish translation
  for every distinct message used by the four exception classes above (the
  `+intl-icu` domain suffix is required for `derafu/translation`&#039;s ICU
  placeholders like `{max}` to be substituted — see
  [ICU Formatting](https://www.derafu.dev/docs/core/translation)).
- `Derafu\DataProcessor\Translation\DataProcessorTranslationResourceProvider`
  — a `TranslationResourceProviderInterface` implementation pointing at
  that directory, ready to hand to a `TranslationResourceRegistrar` or a
  dependency-injection container.

Neither of these does anything by itself — `derafu/data-processor` is a
library, it doesn&#039;t build or own a `Translator`. Activating translation is
entirely up to the application that uses it.

## Activating It (Plain PHP)

```php
use Derafu\DataProcessor\Exception\ValidationException;
use Derafu\DataProcessor\Translation\DataProcessorTranslationResourceProvider;
use Derafu\Translation\TranslatorFactory;

$translator = TranslatorFactory::create(
    defaultLocale: &#039;es&#039;,
    fallbackLocales: [&#039;es&#039;, &#039;en&#039;],
    resourceProviders: [new DataProcessorTranslationResourceProvider()],
);

$e = new ValidationException([&#039;Array must not contain more than {max} items.&#039;, &#039;max&#039; =&gt; 5]);

echo $e-&gt;trans($translator, &#039;es&#039;);
// &quot;El arreglo no debe contener más de 5 elementos.&quot;
```

If you&#039;d rather point at the directory directly (for example, to combine
it with your own translation files) without going through the provider
class, use `TranslationResourceRegistrar` instead:

```php
use Derafu\Translation\TranslationResourceRegistrar;

$registrar = new TranslationResourceRegistrar($translator);
$registrar-&gt;registerDirectory(__DIR__ . &#039;/vendor/derafu/data-processor/resources/translations&#039;);
$registrar-&gt;registerDirectory(__DIR__ . &#039;/translations&#039;); // Your own, registered last: it can override.
```

## Activating It (Dependency Injection)

If your application uses `symfony/dependency-injection`, import both
recipe files and feed the tagged providers into your own `Translator`
registration:

```yaml
imports:
    - { resource: &#039;../vendor/derafu/translation/resources/config/translation-services.yaml&#039; }
    - { resource: &#039;../vendor/derafu/data-processor/resources/config/data-processor-services.yaml&#039; }

services:
    Symfony\Component\Translation\Translator:
        factory: [&#039;Derafu\Translation\TranslatorFactory&#039;, &#039;create&#039;]
        arguments:
            $defaultLocale: &#039;es&#039;
            $fallbackLocales: [&#039;es&#039;, &#039;en&#039;]
            $resourceProviders: !tagged_iterator derafu_translation.resource_provider
```

`data-processor-services.yaml` already tags
`DataProcessorTranslationResourceProvider` with
`derafu_translation.resource_provider`, so it&#039;s picked up automatically —
nothing else to configure. Anything in your own application that
type-hints `Symfony\Contracts\Translation\TranslatorInterface` (as
`derafu/translation`&#039;s own exceptions do) resolves to this `Translator` via
the alias `translation-services.yaml` provides.

## A Note on Rule Names vs. Messages

Rule names (`&#039;email&#039;`, `&#039;max_length&#039;`, the strings you pass to `process()`)
are never translated — they&#039;re an internal API, not user-facing text.
Only the **exception messages** thrown when a rule fails go through
translation.





---
Last updated on 09/11/2026
#php
