PHPackages                             event4u/data-helpers - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. event4u/data-helpers

ActiveLibrary[Database &amp; ORM](/categories/database)

event4u/data-helpers
====================

Framework-agnostic PHP library for data mapping, DTOs and utilities. Includes DataMapper, SimpleDto/LiteDto, DataAccessor/Mutator/Filter and helper classes (MathHelper, EnvHelper, etc.). Works with Laravel, Symfony/Doctrine or standalone PHP.

1.27.0(2mo ago)1421.5k↓12.6%proprietaryPHPPHP ^8.2CI passing

Since Oct 27Pushed 2mo agoCompare

[ Source](https://github.com/event4u-app/data-helpers)[ Packagist](https://packagist.org/packages/event4u/data-helpers)[ GitHub Sponsors](https://github.com/event4u-app)[ GitHub Sponsors](https://github.com/matze4u)[ RSS](/packages/event4u-data-helpers/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (68)Versions (116)Used By (0)

 [ ![event4u Data Helpers](.github/assets/banner.png) ](https://event4u.app)

Data Helpers
============

[](#data-helpers)

[![Packagist Version](https://camo.githubusercontent.com/712a4eb3b0f150a25dcddd4e349a9e6194b0eccc8fec0e103b16c0bad258307e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6576656e7434752f646174612d68656c706572732e7376673f7374796c653d666c61742d737175617265266c6162656c3d7061636b6167697374)](https://packagist.org/packages/event4u/data-helpers)[![PHP](https://camo.githubusercontent.com/7360cc8cdb6c651a5f5438640fbac7cfee9740c5b31ce11add2a015c647eef49/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3737376262333f6c6f676f3d706870266c6f676f436f6c6f723d7768697465267374796c653d666c61742d737175617265)](#installation)[![License: MIT](https://camo.githubusercontent.com/a7e65aee57b11d28e4caff8b945729a66be0bb663f7f93bd24c5aa65699f148e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](#license)[![GitHub Code Quality Action Status](https://camo.githubusercontent.com/e6cc398d23070c9319a04889af7a99bc8e6ac480966256eb4c2f956f954e94e4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6576656e7434752d6170702f646174612d68656c706572732f636f64652d7175616c6974792e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307175616c697479267374796c653d666c61742d737175617265)](https://github.com/event4u-app/data-helpers/actions/workflows/code-quality.yml)[![GitHub PHPStan Action Status](https://camo.githubusercontent.com/568137571bcad24cfd726f65a3a17e7da5816f174b1cd47f3cdcdc5756d13e7c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6576656e7434752d6170702f646174612d68656c706572732f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e267374796c653d666c61742d737175617265)](https://github.com/event4u-app/data-helpers/actions/workflows/phpstan.yml)[![GitHub Test Matrix Action Status](https://camo.githubusercontent.com/c1147d5096e3f3b251184e8b914c428bb1428fd504f2ceea8ca524ba8c01b2ec/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6576656e7434752d6170702f646174612d68656c706572732f746573742d6d61747269782e796d6c3f6272616e63683d6d61696e266c6162656c3d746573742532306d6174726978267374796c653d666c61742d737175617265)](https://github.com/event4u-app/data-helpers/actions/workflows/test-matrix.yml)

**Framework-agnostic PHP library with deep framework integration – get the power of framework-specific solutions without the lock-in.**

Transform complex data structures, create type-safe DTOs and simplify data operations with expressive syntax. Works standalone in **Pure PHP** or with **deep integration** for Laravel and Symfony. Includes DataMapper, SimpleDto/LiteDto, DataAccessor/Mutator/Filter and utility helpers (MathHelper, EnvHelper, etc.).

```
// From this messy API response...
$apiResponse = [
    'data' => [
        'departments' => [
            ['users' => [['email' => 'alice@example.com'], ['email' => 'bob@example.com']]],
            ['users' => [['email' => 'charlie@example.com']]],
        ],
    ],
];

// ...to this clean result in a few lines
$accessor = new DataAccessor($apiResponse);
$emails = $accessor->get('data.departments.*.users.*.email');
// ['alice@example.com', 'bob@example.com', 'charlie@example.com']
```

**🎯 Framework-Agnostic + Deep Integration** • Pure PHP with **zero dependencies** • Optional **Laravel** &amp; **Symfony** integration • No framework lock-in

📖 **[Full Documentation](https://event4u-app.github.io/data-helpers/)** • [Getting Started](https://event4u-app.github.io/data-helpers/getting-started/quick-start/) • [API Reference](https://event4u-app.github.io/data-helpers/api/)

💖 **[Support the Development](#-sponsoring)** - Help us build better tools for the PHP community

---

💡 Why Data Helpers?
-------------------

[](#-why-data-helpers)

### 🎯 Stop Writing Nested Loops

[](#-stop-writing-nested-loops)

```
// ❌ Without Data Helpers
$emails = [];
foreach ($data['departments'] ?? [] as $dept) {
    foreach ($dept['users'] ?? [] as $user) {
        if (isset($user['email'])) {
            $emails[] = $user['email'];
        }
    }
}

// ✅ With Data Helpers
$emails = $accessor->get('departments.*.users.*.email');
```

### 🚀 Key Benefits

[](#-key-benefits)

- **🎯 Framework-Agnostic + Deep Integration** - Pure PHP with zero dependencies, optional deep Laravel/Symfony integration
- **Type-Safe** - PHPStan Level 9 compliant with 4700+ tests

- **Fast** - SimpleDto with #\[UltraFast\] is up to 12.5x faster than Other Serializer

- **Zero Dependencies** - No required dependencies, optional framework integrations
- **No Framework Lock-In** - Use framework features without being tied to a framework
- **No-Code Mapping** - Store templates in database, create with drag-and-drop editors

---

📦 Installation
--------------

[](#-installation)

```
composer require event4u/data-helpers
```

**Requirements:** PHP 8.2+

**Framework support** (all optional):

- 🔴 **Laravel** 9+ - Collections, Eloquent Models
- ⚫ **Symfony/Doctrine** 6+ - Collections, Entities
- 🔧 **Standalone PHP** - Works out of the box

📖 **[Installation Guide](https://event4u-app.github.io/data-helpers/getting-started/installation/)** • [Configuration](https://event4u-app.github.io/data-helpers/getting-started/configuration/)

---

🔌 Framework Integration
-----------------------

[](#-framework-integration)

**The best of both worlds:** Use Data Helpers as a **standalone library** in pure PHP, or leverage **deep framework integration** for Laravel and Symfony – without framework lock-in.

### 🎯 Framework-Agnostic Core

[](#-framework-agnostic-core)

**Zero dependencies required.** Works out of the box with:

- ✅ **Pure PHP** - Arrays, objects, JSON, XML
- ✅ **Any Framework** - No framework-specific code required
- ✅ **Portable** - Move between frameworks without code changes

```
// Works everywhere - no framework needed
$dto = UserDto::fromArray(['name' => 'John', 'email' => 'john@example.com']);
$json = json_encode($dto);
```

### 🚀 Optional Deep Integration

[](#-optional-deep-integration)

**When you need it:** Add framework-specific features without changing your core code.

#### Laravel Integration (Optional)

[](#laravel-integration-optional)

```
// 1. Controller Injection - Automatic validation & filling
class UserController extends Controller
{
    public function store(UserDto $dto): JsonResponse
    {
        // $dto is automatically validated and filled from request
        $user = User::create($dto->toArray());
        return response()->json($user, 201);
    }
}

// 2. Eloquent Model Integration
$user = User::find(1);
$dto = UserDto::fromModel($user);  // From Model
$dto->toModel($user);              // To Model

// 3. Laravel-Specific Attributes
class UserProfileDto extends SimpleDto
{
    public function __construct(
        public readonly string $name,

        #[WhenAuth]  // Only when authenticated
        public readonly ?string $email = null,

        #[WhenCan('edit-posts')]  // Only with permission
        public readonly ?string $editUrl = null,

        #[WhenRole('admin')]  // Only for admins
        public readonly ?array $adminPanel = null,
    ) {}
}

// 4. Artisan Commands
php artisan make:dto UserDto
php artisan dto:typescript
php artisan dto:migrate-spatie
```

#### Symfony Integration (Optional)

[](#symfony-integration-optional)

```
// 1. Controller Injection - Automatic validation & filling
class UserController extends AbstractController
{
    #[Route('/users', methods: ['POST'])]
    public function create(UserDto $dto): JsonResponse
    {
        // $dto is automatically validated and filled from request
        $user = new User();
        $dto->toEntity($user);
        $this->entityManager->persist($user);
        $this->entityManager->flush();
        return $this->json($user, 201);
    }
}

// 2. Doctrine Entity Integration
$user = $this->entityManager->find(User::class, 1);
$dto = UserDto::fromEntity($user);  // From Entity
$dto->toEntity($user);              // To Entity

// 3. Symfony-Specific Attributes
class UserProfileDto extends SimpleDto
{
    public function __construct(
        public readonly string $name,

        #[WhenGranted('ROLE_ADMIN')]  // Only with permission
        public readonly ?string $email = null,

        #[WhenSymfonyRole('ROLE_MODERATOR')]  // Only for moderators
        public readonly ?array $moderationPanel = null,
    ) {}
}

// 4. Console Commands
php bin/console make:dto UserDto
php bin/console dto:typescript
```

### 💡 Key Integration Features

[](#-key-integration-features)

FeaturePure PHPLaravelSymfony**DTOs &amp; Validation**✅✅✅**Controller Injection**❌✅ Auto✅ Auto**Request Validation**✅ Manual✅ Auto✅ Auto**Model/Entity Mapping**✅ Plain Objects✅ Eloquent✅ Doctrine**Framework Attributes**❌✅ Auth/Can/Role✅ Granted/Role**Code Generation**❌✅ Artisan✅ Console**TypeScript Export**❌✅✅**The Power:** Get framework-specific features when you need them, without framework dependencies in your core code.

📖 **[Laravel Integration Guide](https://event4u-app.github.io/data-helpers/framework-integration/laravel/)** • [Symfony Integration Guide](https://event4u-app.github.io/data-helpers/framework-integration/symfony/)

---

⚡ Core Components
-----------------

[](#-core-components)

**The heart of this library:** Data mapping and DTOs for transforming and structuring data, plus powerful data manipulation tools.

### 1️⃣ DataAccessor - Read &amp; Transform Data

[](#1️⃣-dataaccessor---read--transform-data)

Access deeply nested data with dot notation, wildcards, and powerful transformation methods:

```
$data = [
    'users' => [
        ['name' => 'Alice', 'age' => '30', 'email' => 'alice@example.com'],
        ['name' => 'Bob', 'age' => '25', 'email' => 'bob@example.com'],
    ],
];

$accessor = new DataAccessor($data);

// Generic get() - returns mixed
$emails = $accessor->get('users.*.email');
// ['users.0.email' => 'alice@example.com', 'users.1.email' => 'bob@example.com']

// Type-safe getters - strict type conversion with nullable return
$name = $accessor->getString('users.0.name');  // 'Alice'
$age = $accessor->getInt('users.0.age');       // 30 (string → int)
$missing = $accessor->getString('users.0.phone');  // null

// Collection getters for wildcards - returns DataCollection instances
$ages = $accessor->getIntCollection('users.*.age');  // DataCollection
$names = $accessor->getStringCollection('users.*.name');  // DataCollection

// Transformation methods - filter, map, reduce directly on DataAccessor
$filtered = $accessor->filter(fn($user) => $user['age'] > 25);  // [['name' => 'Alice', ...]]
$mapped = $accessor->map(fn($user) => $user['name']);  // ['Alice', 'Bob']
$sum = $accessor->reduce(fn($carry, $user) => $carry + $user['age'], 0);  // 55

// first() and last() with optional callback
$firstUser = $accessor->first();  // ['name' => 'Alice', ...]
$lastAdult = $accessor->last(fn($user) => $user['age'] >= 18);

// Lazy evaluation for large datasets
foreach ($accessor->lazyFilter(fn($user) => $user['age'] > 25) as $user) {
    // Process items one at a time without loading all into memory
}
```

📖 **[DataAccessor Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-accessor/)**

### 2️⃣ DataCollection - Type-Safe Collections

[](#2️⃣-datacollection---type-safe-collections)

Framework-independent collection class with fluent API. Uses DataAccessor for reading, DataMutator for writing, and DataFilter for SQL-like querying:

```
use event4u\DataHelpers\DataCollection;

$collection = DataCollection::make([1, 2, 3, 4, 5]);

// Filter, map, reduce with method chaining (delegates to DataAccessor)
$result = $collection
    ->filter(fn($item) => $item > 2)  // [3, 4, 5]
    ->map(fn($item) => $item * 2)     // [6, 8, 10]
    ->reduce(fn($carry, $item) => $carry + $item, 0);  // 24

// Dot-notation read access (via DataAccessor)
$collection = DataCollection::make([
    ['user' => ['name' => 'Alice', 'age' => 30]],
    ['user' => ['name' => 'Bob', 'age' => 25]],
]);
$name = $collection->get('0.user.name');  // 'Alice'

// Dot-notation write access (via DataMutator) - modifies in-place
$collection
    ->set('0.user.city', 'Berlin')
    ->merge('1.user', ['city' => 'Munich', 'country' => 'Germany'])
    ->transform('0.user.name', fn($name) => strtoupper($name));

// SQL-like filtering (via DataFilter) - returns new DataCollection
$users = DataCollection::make([
    ['name' => 'Alice', 'age' => 30, 'city' => 'Berlin'],
    ['name' => 'Bob', 'age' => 25, 'city' => 'Munich'],
    ['name' => 'Charlie', 'age' => 35, 'city' => 'Berlin'],
]);
$filtered = $users
    ->query()
    ->where('age', '>', 25)
    ->where('city', 'Berlin')
    ->orderBy('age', 'DESC')
    ->get();  // Returns new DataCollection

// Lazy evaluation for large datasets
foreach ($collection->lazyFilter(fn($item) => $item > 2) as $item) {
    // Process items one at a time without loading all into memory
}
```

📖 **[DataCollection Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-collection/)**

### 3️⃣ DataMutator - Modify Nested Data

[](#3️⃣-datamutator---modify-nested-data)

Safely modify nested structures:

```
$data = ['user' => ['profile' => []]];
DataMutator::make($data)
    ->set('user.profile.name', 'Alice')
    ->merge('user.profile', ['age' => 30]);
// $data is now modified: ['user' => ['profile' => ['name' => 'Alice', 'age' => 30]]]
```

📖 **[DataMutator Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-mutator/)**

### 4️⃣ DataFilter - Query Data

[](#4️⃣-datafilter---query-data)

Filter and query data with SQL-like API:

```
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 3, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 400],
];

$result = DataFilter::query($products)
    ->where('category', '=', 'Electronics')
    ->where('price', '>', 100)
    ->orderBy('price', 'DESC')
    ->get();
// Result: [Laptop ($1200), Monitor ($400)]
```

📖 **[DataFilter Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-filter/)**

### 5️⃣ SimpleDto - Immutable Dtos

[](#5️⃣-simpledto---immutable-dtos)

Create type-safe, immutable Data Transfer Objects with automatic type casting and multi-format serialization (JSON, XML, YAML, CSV):

```
use event4u\DataHelpers\SimpleDto\Attributes\NoCasts;

// Default: Automatic type casting enabled
class ReadmeUserDto extends SimpleDto
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly int $age,
        public readonly AddressDto $address,  // Nested DTO (auto-cast by default)
    ) {}
}

// Automatic type conversion by default
$user = ReadmeUserDto::fromArray([
    'name' => 'John',
    'email' => 'john@example.com',
    'age' => '30',  // String "30" → int 30 (automatic)
    'address' => ['city' => 'Berlin'],  // Array → AddressDto (automatic)
]);

// Disable automatic casting for better performance
#[NoCasts]
class StrictUserDto extends SimpleDto
{
    public function __construct(
        public readonly string $name,
        public readonly int $age,  // Must be int, no conversion
        public readonly AddressDto $address,  // Must be AddressDto instance, no conversion
    ) {}
}

// Multi-format serialization
$json = $user->toJson();  // JSON
$xml = $user->toXml();    // XML
$yaml = $user->toYaml();  // YAML
$csv = $user->toCsv();    // CSV
```

📖 **[SimpleDto Documentation](https://event4u-app.github.io/data-helpers/simple-dto/introduction/)**

#### Plain PHP Object Integration

[](#plain-php-object-integration)

SimpleDto seamlessly integrates with plain PHP objects (like Zend Framework models or any plain PHP classes):

```
use event4u\DataHelpers\SimpleDto;
use event4u\DataHelpers\SimpleDto\Attributes\HasObject;
use event4u\DataHelpers\SimpleDto\SimpleDtoObjectTrait;

// Plain PHP object
class Product
{
    public int $id;
    public string $name;
    public float $price;
}

// DTO with plain object integration
#[HasObject(Product::class)]
class ProductDto extends SimpleDto
{
    use SimpleDtoObjectTrait;

    public function __construct(
        public readonly int $id,
        public readonly string $name,
        public readonly float $price,
    ) {}
}

// Object → DTO
$product = new Product();
$product->id = 1;
$product->name = 'Laptop';
$product->price = 999.99;
$dto = ProductDto::fromObject($product);

// DTO → Object
$newProduct = $dto->toObject();  // Uses HasObject attribute
```

**Also works with getters/setters:**

```
class Customer
{
    private int $id;
    private string $name;

    public function getId(): int { return $this->id; }
    public function setId(int $id): void { $this->id = $id; }
    public function getName(): string { return $this->name; }
    public function setName(string $name): void { $this->name = $name; }
}

// fromObject() uses getters, toObject() uses setters
$dto = CustomerDto::fromObject($customer);
$newCustomer = $dto->toObject(Customer::class);
```

📖 **[Plain Object Integration Guide](docs/plain-object-integration.md)** • [Example Code](examples/plain-object-example.php)

### 6️⃣ LiteDto - Ultra-Fast Dtos

[](#6️⃣-litedto---ultra-fast-dtos)

Create ultra-fast, minimalistic DTOs with essential features:

```
use event4u\DataHelpers\LiteDto;
use event4u\DataHelpers\LiteDto\Attributes\MapFrom;
use event4u\DataHelpers\LiteDto\Attributes\Hidden;

class UserDto extends LiteDto
{
    public function __construct(
        public readonly string $name,

        #[MapFrom('email_address')]
        public readonly string $email,

        #[Hidden]
        public readonly string $password,
    ) {}
}

$user = UserDto::from([
    'name' => 'John',
    'email_address' => 'john@example.com',
    'password' => 'secret',
]);

$array = $user->toArray();
// ['name' => 'John', 'email' => 'john@example.com']
// password is hidden
```

**Performance**: LiteDto is **7.6x faster** than SimpleDto Normal (~2.3μs vs ~18.5μs)

📖 **[LiteDto Documentation](https://event4u-app.github.io/data-helpers/lite-dto/introduction/)**

### 3️⃣ DataMapper - Transform Data

[](#3️⃣-datamapper---transform-data)

Map between different data structures with templates. Supports multi-format output (JSON, XML, YAML, CSV):

```
$source = [
    'user' => ['name' => 'John Doe', 'email' => 'john@example.com'],
    'orders' => [
        ['id' => 1, 'status' => 'shipped', 'total' => 100],
        ['id' => 2, 'status' => 'pending', 'total' => 50],
        ['id' => 3, 'status' => 'shipped', 'total' => 200],
    ],
];

$result = DataMapper::from($source)
    ->template([
        'customer_name' => '{{ user.name }}',
        'customer_email' => '{{ user.email }}',
        'shipped_orders' => [
            'WHERE' => [
                '{{ orders.*.status }}' => 'shipped',
            ],
            'ORDER BY' => [
                '{{ orders.*.total }}' => 'DESC',
            ],
            '*' => [
                'id' => '{{ orders.*.id }}',
                'total' => '{{ orders.*.total }}',
            ],
        ],
    ])
    ->map()
    ->getTarget();
```

**💡 No-Code Data Mapping:** Templates can be stored in a database and created with a drag-and-drop editor - perfect for import wizards, API integrations and ETL pipelines without writing code!

**⚠️ XML Files:** When loading XML files with `sourceFile()`, the root element name is preserved. Always include it in your paths: `'{{ company.name }}'` for `...`.

📖 **[DataMapper Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/)**

### 7️⃣ Utility Helpers - Common Data Operations

[](#7️⃣-utility-helpers---common-data-operations)

Simplify common data operations with specialized helper classes:

```
use event4u\DataHelpers\Helpers\MathHelper;
use event4u\DataHelpers\Helpers\EnvHelper;

// Math operations with precision
$result = MathHelper::add('10.5', '20.3', 2);  // 30.8
$average = MathHelper::average([10, 20, 30]);  // 20.0
$sum = MathHelper::sum([5, 10, 15]);  // 30.0

// Environment variable access with type casting
$debug = EnvHelper::boolean('APP_DEBUG', false);
$port = EnvHelper::integer('APP_PORT', 8080);
$timeout = EnvHelper::float('REQUEST_TIMEOUT', 30.0);
```

**Available Helpers:**

- **MathHelper** - Precision math operations using bcmath (add, subtract, multiply, divide, modulo, powerOf, squareRoot, compare, min, max, sum, average, product, time conversions)
- **EnvHelper** - Type-safe environment variable access with framework detection (get, has, string, integer, float, boolean, array)
- **ConfigHelper** - Singleton configuration manager with framework detection and dot notation (getInstance, get, getBoolean, getInteger, getFloat, getString, getArray, has, set, reset)
- **DotPathHelper** - Dot notation path utilities with wildcard support (segments, buildPrefix, isWildcard, containsWildcard)
- **ObjectHelper** - Deep object cloning with recursion control (copy)

📖 **[Helpers Documentation](https://event4u-app.github.io/data-helpers/helpers/overview/)**

---

🎯 Advanced Features
-------------------

[](#-advanced-features)

### No-Code Data Mapping

[](#no-code-data-mapping)

**Store templates in database and create mappings without programming:**

```
// Load template from database (created with drag-and-drop editor)
$template = Mappings::find(3)->template;

$result = DataMapper::from($source)
    ->template($template)
    ->map()
    ->getTarget();
```

**Perfect for:**

- 📥 **Import Wizards** - Let users map CSV/Excel columns to your data model
- 🔌 **API Integration** - Configure API mappings without code changes
- 🏢 **Multi-Tenant Systems** - Each tenant can have custom data mappings
- 🔄 **Dynamic ETL** - Build data transformation pipelines visually
- 📝 **Form Builders** - Map form submissions to different data structures

📖 **[Template-Based Mapping Guide](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/)**

### Complex Nested Mapping

[](#complex-nested-mapping)

Map complex nested structures to Eloquent Models or Doctrine Entities:

```
// Automatic relation detection for Eloquent/Doctrine
$company = new Company();
$result = DataMapper::from($jsonData)
    ->target($company)
    ->template([
        'name' => '{{ company.name }}',
        'departments' => [
            '*' => [
                'name' => '{{ company.departments.*.name }}',
                'budget' => '{{ company.departments.*.budget }}',
            ],
        ],
    ])
    ->map()
    ->getTarget();
```

- ✅ Automatic Relation Detection
- ✅ Type Casting (string → int/float/bool)
- ✅ Snake\_case → camelCase conversion
- ✅ Nested Wildcards

📖 **[Advanced Mapping Guide](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/)**

### Pipeline API

[](#pipeline-api)

Transform data with composable filters:

```
use Tests\Utils\Docu\TrimStrings;
use Tests\Utils\Docu\LowercaseEmails;
use Tests\Utils\Docu\SkipEmptyValues;

$source = ['name' => '  John  ', 'email' => 'JOHN@EXAMPLE.COM'];
$mapping = ['name' => '{{ name }}', 'email' => '{{ email }}'];

$result = DataMapper::from($source)
    ->template($mapping)
    ->pipeline([
        new TrimStrings(),
        new LowercaseEmails(),
        new SkipEmptyValues(),
    ])
    ->map()
    ->getTarget();

// $result = ['name' => 'John', 'email' => 'john@example.com']
```

📖 **[Pipeline Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/pipelines/)**

### Template Expressions

[](#template-expressions)

Use Twig-like expressions with 18+ built-in filters:

```
$mapping = [
    'name' => '{{ user.firstName | ucfirst }} {{ user.lastName | ucfirst }}',
    'email' => '{{ user.email | lower | trim }}',
    'role' => '{{ user.role | upper ?? "USER" }}',
];
```

📖 **[Template Expressions](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/template-expressions/)**

### Query Builder

[](#query-builder)

Laravel-style fluent interface for building queries:

```
$result = DataMapper::query()
    ->source('products', $data)
    ->where('category', 'Electronics')
    ->where('price', '>', 100)
    ->orderBy('price', 'DESC')
    ->groupBy('category', ['total' => ['COUNT']])
    ->get();
```

📖 **[Query Builder Documentation](https://event4u-app.github.io/data-helpers/main-classes/data-mapper/query-builder/)**

---

📚 Documentation
---------------

[](#-documentation)

**Comprehensive documentation with guides, examples and API reference is available at:**

🔗 **[event4u-app.github.io/data-helpers](https://event4u-app.github.io/data-helpers/)**

The documentation includes:

- 📖 **Getting Started Guides** - Installation, configuration and quick start tutorials
- 🔧 **Main Classes** - Detailed guides for DataAccessor, DataMutator, DataMapper and DataFilter
- 🎯 **SimpleDto** - Type-safe Dtos with validation, casting and collections
- ⚡ **LiteDto** - Ultra-fast, minimalistic Dtos (7.6x faster than SimpleDto)
- 🚀 **Advanced Features** - Template expressions, query builder, pipelines and reverse mapping
- 🔌 **Framework Integration** - Laravel, Symfony and Doctrine integration guides
- 💡 **90+ Code Examples** - Runnable examples for every feature
- 📊 **Performance Benchmarks** - Optimization tips and benchmark results
- 🔍 **Complete API Reference** - Full API documentation for all classes and methods

---

🧪 Testing &amp; Quality
-----------------------

[](#-testing--quality)

- ✅ **4700+ tests** with comprehensive coverage
- ✅ **PHPStan Level 9** - Highest static analysis level
- ✅ **100% type coverage** - All methods fully typed
- ✅ **Continuous Integration** - Automated testing across PHP 8.2, 8.3, 8.4

📖 **[Contributing Guide](https://event4u-app.github.io/data-helpers/guides/contributing/)** • [Development Setup](https://event4u-app.github.io/data-helpers/guides/development-setup/)

---

⚡ Performance
-------------

[](#-performance)

All operations are highly optimized:

- Simple access: ~0.0μs
- Nested access: ~0.4μs
- Wildcards: ~1μs
- **SimpleDto #\[UltraFast\] is up to 12.5x faster** than Other Serializer

📖 **[Performance Benchmarks](https://event4u-app.github.io/data-helpers/performance/benchmarks/)** • [Optimization Tips](https://event4u-app.github.io/data-helpers/performance/optimization/)

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please see the [Contributing Guide](https://event4u-app.github.io/data-helpers/guides/contributing/) for details.

```
# Install dependencies
composer install

# Run tests
composer test

# Run quality checks
composer quality
```

---

💖 Sponsoring
------------

[](#-sponsoring)

This package is part of the **event4u** ecosystem - a comprehensive event management platform. Your sponsorship helps us:

- 🚀 **Develop event4u** - The next-generation event management app
- 📦 **Maintain open-source packages** - Like this Data Helpers library
- 🔧 **Build new tools** - More packages and utilities for the PHP community
- 📚 **Improve documentation** - Better guides and examples
- 🐛 **Fix bugs faster** - Dedicated time for maintenance and support

### Support the Development

[](#support-the-development)

 [ ![Sponsor @matze4u](https://camo.githubusercontent.com/853b633cc81ff3ae9c47eaf67066535aea5dc1cb7a3d259168cd23da16355209/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d406d61747a6534752d6561353032373f7374796c653d666f722d7468652d6261646765266c6f676f3d6769746875622d73706f6e736f7273266c6f676f436f6c6f723d7768697465) ](https://github.com/sponsors/matze4u) [ ![Sponsor event4u-app](https://camo.githubusercontent.com/6d0ad353b5766fd282e277cd53e844f1fa11459a28b2d82c6e8330ce8c030e09/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d6576656e7434752d2d6170702d6561353032373f7374796c653d666f722d7468652d6261646765266c6f676f3d6769746875622d73706f6e736f7273266c6f676f436f6c6f723d7768697465) ](https://github.com/sponsors/event4u-app)

Every contribution, no matter how small, makes a difference and is greatly appreciated! 🙏

---

📄 License
---------

[](#-license)

MIT License. See [LICENSE](LICENSE) for details.

---

🌟 Show Your Support
-------------------

[](#-show-your-support)

If this package helps you, please consider:

- ⭐ Giving it a star on GitHub
- 💖 [Sponsoring the development](https://github.com/sponsors/event4u-app)
- 📢 Sharing it with others

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance87

Actively maintained with recent releases

Popularity36

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

65

Last Release

65d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/351a95acbe6b88310de48ea00204e58b0ea216cb1160a3130ffd3dc0b42ef448?d=identicon)[matze4u](/maintainers/matze4u)

---

Top Contributors

[![matze4u](https://avatars.githubusercontent.com/u/171579628?v=4)](https://github.com/matze4u "matze4u (352 commits)")

---

Tags

phpsymfonylaravelvalidationhelpersdatadoctrinefiltermappingmapperdata-transfer-objecttransformationdtoutilitiesaccessormutator

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleECS

Type Coverage Yes

### Embed Badge

![Health badge](/badges/event4u-data-helpers/health.svg)

```
[![Health](https://phpackages.com/badges/event4u-data-helpers/health.svg)](https://phpackages.com/packages/event4u-data-helpers)
```

###  Alternatives

[doctrine/mongodb-odm

PHP Doctrine MongoDB Object Document Mapper (ODM) provides transparent persistence for PHP objects to MongoDB.

1.1k23.3M302](/packages/doctrine-mongodb-odm)[rekalogika/mapper

An object mapper for PHP and Symfony. Maps an object to another object. Primarily used for transforming an entity to a DTO and vice versa.

3847.7k1](/packages/rekalogika-mapper)[yorcreative/laravel-argonaut-dto

Argonaut is a lightweight Data Transfer Object (DTO) package for Laravel that supports nested casting, recursive serialization, and validation out of the box. Ideal for service layers, APIs, and clean architecture workflows.

1062.8k1](/packages/yorcreative-laravel-argonaut-dto)[fourlabs/qbjs-parser-bundle

This bundle is a Symfony wrapper for fourlabs/qbjs-parser.

1514.7k1](/packages/fourlabs-qbjs-parser-bundle)[fab2s/dt0

Immutable DTOs with bidirectional casting. No framework required. 8x faster than the alternative.

101.6k1](/packages/fab2s-dt0)[bauer01/unimapper-flexibee

Flexibee implementation for UniMapper

101.1k](/packages/bauer01-unimapper-flexibee)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
