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

# Derafu Data Processor



---

## Introduction

Four-Phase Data Processing Library

# Four-Phase Data Processing Library

![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.
- **Almost Zero Dependencies**: just `intl` extension for specific format rules and `Carbon` for dates.

## Features

- 🎯 **Type-Safe Casting**: Convert between data types safely.
  - Basic types (string, int, float, bool).
  - Date and time handling.

- 🔄 **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, etc.).
  - File validations (file, image, mime_types).
  - Array validations (min_items, max_items, not_empty, etc.).

## Installation

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

## Basic Usage

```php
use Derafu\DataProcessor\ProcessorFactory;

$processor = ProcessorFactory::create();

// 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;mime_types:application/pdf,image/jpeg&#039;]
]);
```




---

## Rules Reference

Rules Reference

# Rules Reference

## Cast Rules

| Rule | Description | Example |
|------|-------------|---------|
| `boolean`, `bool` | Convert value to boolean | `&#039;cast&#039; =&gt; &#039;boolean&#039;` |
| `date` | Convert value to Carbon date | `&#039;cast&#039; =&gt; &#039;date&#039;` |
| `datetime` | Convert value to Carbon datetime | `&#039;cast&#039; =&gt; &#039;datetime&#039;` |
| `float`, `decimal` | Convert value to float | `&#039;cast&#039; =&gt; &#039;float&#039;` |
| `integer`, `int` | Convert value to integer | `&#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 | `&#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 non-printable characters | `&#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 whitespace from ends | `&#039;sanitize&#039; =&gt; [&#039;trim&#039;]` |

## Validate Rules

### Array Validation

| Rule | Description | Example |
|------|-------------|---------|
| `in`, `choices` | Check if value is in list | `&#039;validate&#039; =&gt; [&#039;in:a,b,c&#039;]` |
| `max_items` | Check array maximum length | `&#039;validate&#039; =&gt; [&#039;max_items:5&#039;]` |
| `min_items` | Check array minimum length | `&#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 | `&#039;validate&#039; =&gt; [&#039;unique&#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;]` |
| `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 limit | `&#039;validate&#039; =&gt; [&#039;file:2M&#039;]` |
| `image` | Validate image file with size limit | `&#039;validate&#039; =&gt; [&#039;image:2M&#039;]` |
| `mimetype` | Validate file mime type | `&#039;validate&#039; =&gt; [&#039;mimetype:application/pdf,image/jpeg&#039;]` |

### Financial Validation

| Rule | Description | Example |
|------|-------------|---------|
| `bic` | Validate BIC/SWIFT code | `&#039;validate&#039; =&gt; [&#039;bic&#039;]` |
| `card_number` | Validate credit card number | `&#039;validate&#039; =&gt; [&#039;card_number&#039;]` |
| `iban` | Validate IBAN | `&#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 currency code | `&#039;validate&#039; =&gt; [&#039;currency&#039;]` |
| `language` | Validate language code | `&#039;validate&#039; =&gt; [&#039;language&#039;]` |
| `locale` | Validate locale code | `&#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 | `&#039;validate&#039; =&gt; [&#039;uuid&#039;]` |

### Internet Validation

| Rule | Description | Example |
|------|-------------|---------|
| `email` | Validate email address | `&#039;validate&#039; =&gt; [&#039;email&#039;]` |
| `hostname` | Validate hostname | `&#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 | `&#039;validate&#039; =&gt; [&#039;url&#039;]` |

### Numeric Validation

| Rule | Description | Example |
|------|-------------|---------|
| `decimal`, `float`, `real` | Validate decimal number | `&#039;validate&#039; =&gt; [&#039;decimal:2&#039;]` |
| `digits_range` | Validate number of digits range | `&#039;validate&#039; =&gt; [&#039;digits_range:3,5&#039;]` |
| `digits` | Validate exact 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;]` |
| `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 | `&#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;]` |




---

## 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;addTransformRule(&#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 Custom Rule Registrar

# Creating Custom Rule Registrar

For better organization, you can create a custom rule registrar:

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

final class CustomRuleRegistrar implements RuleRegistrarInterface
{
    public function register(RuleRegistryInterface $registry): void
    {
        // Register caster rules.
        $registry
            -&gt;addCasterRule(&#039;custom_type_1&#039;, CustomType1Rule::class)
            -&gt;addCasterRule(&#039;custom_type_2&#039;, CustomType2Rule::class);

        // Register transform rules.
        $registry
            -&gt;addTransformRule(&#039;custom_transform_1&#039;, CustomTransform1Rule::class)
            -&gt;addTransformRule(&#039;custom_transform_2&#039;, CustomTransform2Rule::class);

        // Register sanitizer rules.
        $registry
            -&gt;addSanitizerRule(&#039;custom_sanitize_1&#039;, CustomSanitize1Rule::class)
            -&gt;addSanitizerRule(&#039;custom_sanitize_2&#039;, CustomSanitize2Rule::class);

        // Register validator rules.
        $registry
            -&gt;addValidatorRule(&#039;custom_validate_1&#039;, CustomValidate1Rule::class)
            -&gt;addValidatorRule(&#039;custom_validate_2&#039;, CustomValidate2Rule::class);
    }
}

// Usage.
$processor = ProcessorFactory::create(
    new CustomRuleRegistrar(),
    withDefaultRules: false // Create without default rules using the factory.
);
```

This allows you to:

- Create domain-specific rule sets.
- Override default rules with custom implementations.
- Group related rules together.
- Control which rules are available in your application.




---

## Custom Parser

Creating Custom Rule Parser

# Creating Custom Rule Parser

You can create your own rule parser to customize how rules are parsed from strings or arrays:

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

final class CustomRuleParser implements RuleParserInterface
{
    public function parse(string|array $rules): array
    {
        if (is_array($rules)) {
            return $this-&gt;parseArray($rules);
        }
        return $this-&gt;parseString($rules);
    }

    private function parseArray(array $rules): array
    {
        // Your array parsing logic here.
        $parsed = [];
        foreach ($rules as $type =&gt; $typeRules) {
            // Handle different formats for rules.
            $parsed[$type] = $this-&gt;parseTypeRules($typeRules);
        }
        return $parsed;
    }

    private function parseString(string $rules): array
    {
        // Your string parsing logic here.
        // Example: parse rules like &quot;t(rule1|rule2) s(rule3) required|email&quot;
        return [
            &#039;transform&#039; =&gt; [&#039;rule1&#039;, &#039;rule2&#039;],
            &#039;sanitize&#039; =&gt; [&#039;rule3&#039;],
            &#039;validate&#039; =&gt; [&#039;required&#039;, &#039;email&#039;],
        ];
    }

    private function parseTypeRules(string|array $rules): array|string
    {
        // Handle parsing of individual rule types.
        if (is_string($rules)) {
            return explode(&#039;|&#039;, $rules);
        }
        return $rules;
    }
}

// Usage with processor factory.
$processor = ProcessorFactory::create(
    parser: new CustomRuleParser()
);

// Or manual instantiation.
$registry = new RuleRegistry(); // Then register the rules you need.
$resolver = new RuleResolver($registry);
$parser = new CustomRuleParser();
$processor = new Processor($resolver, $parser);

// Using your custom parser.
$result = $processor-&gt;process(&#039;test@example.com&#039;, &#039;t(lowercase) s(trim) required|email&#039;);

// Or.
$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;required|email&#039;,
]);
```

This allows you to:

- Create custom rule parsing formats.
- Support different string formats for rules.
- Add custom shorthand notations.
- Implement domain-specific rule syntax.
- Handle complex rule configurations.





---
Last updated on 24/08/2026
#php
