centamiv/cast

A strictly typed, zero-dependency PHP object-to-object mapping library.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/centamiv/cast

dev-master 2025-12-22 07:43 UTC

This package is auto-updated.

Last update: 2025-12-22 07:43:16 UTC


README

Cast is a lightweight, strictly typed, zero-dependency PHP library for object-to-object mapping. It allows you to transform entities into DTOs (and vice-versa) using a fluent API and a "convention over configuration" approach.

Features

  • Zero Dependencies: Pure PHP 8.2+ implementation.
  • Strict Types: Built with declare(strict_types=1).
  • Automapping: Automatically maps properties with the same name.
  • Fluent Interface: Clean and readable API (Cast::from($src)->to(Target::class)).
  • Inline Mapping: Define rules directly in the chain (Cast::from($src)->map([...])->to(...)).
  • Transformers: Built-in helpers for common type conversions.
  • Callbacks: Custom transformation logic via closures.
  • Recursive: Automatically handles arrays and collections.
  • Private Properties: Works with private and protected properties via Reflection.

Installation

composer require centamiv/cast

Usage

1. Basic Mapping (Automapping)

If your source and target classes have properties with the same names, mapping is automatic.

use Centamiv\Cast\Cast;

class User {
    public function __construct(
        public int $id,
        public string $name
    ) {}
}

class UserDto {
    public int $id;
    public string $name;
}

$user = new User(1, 'Mario');

// Maps 'id' and 'name' automatically
$dto = Cast::from($user)->to(UserDto::class); 

2. Custom Transformations (Cast::define)

For complex mappings, renaming, or nested objects, you can define rules using Cast::define().

use Centamiv\Cast\Cast;

// Configuration (e.g., in a bootstrap file or ServiceProvider)
Cast::define(Order::class, OrderDto::class, [
    // Simple Rename: source property 'customer_name' -> target property 'client'
    'client' => 'customer_name',
    
    // Custom Callback: formatting value
    'total' => fn(Order $o) => '' . number_format($o->amount, 2),
    
    // Nested Mapping: transform array of Items to array of ItemDtos
    'items' => fn(Order $o) => Cast::from($o->getItems())->to(ItemDto::class)
]);

// Execution
$order = $repository->find(123);
$dto = Cast::from($order)->to(OrderDto::class);

3. Inline Mapping

You can also define mapping rules directly in the fluent chain, without using Cast::define(). This is useful for one-off transformations. Inline rules merge with and override global definitions.

$dto = Cast::from($user)
    ->map([
        'fullName' => fn($u) => $u->firstName . ' ' . $u->lastName,
        'isActive' => Cast::toBool('status')
    ])
    ->to(UserDto::class);

4. Transformers

The library provides built-in transformer methods directly on the Cast facade to simplify common type conversions.

use Centamiv\Cast\Cast;

Cast::define(Product::class, ProductDto::class, [
    // Cast 'status_int' (0/1) to boolean
    'isActive' => Cast::toBool('status_int'),
    
    // Cast 'price_string' to float
    'price' => Cast::toFloat('price_string'),
    
    // Convert string to DateTimeImmutable (default format: Y-m-d H:i:s)
    'createdAt' => Cast::toDateTime('created_at'),
    
    // Custom format
    'birthDate' => Cast::toDateTime('dob', 'd/m/Y')
]);

Available transformers:

  • Cast::toInt(string $property)
  • Cast::toFloat(string $property)
  • Cast::toString(string $property)
  • Cast::toBool(string $property)
  • Cast::toDateTime(string $property, string $format = 'Y-m-d H:i:s')

5. Collections

Cast detects iterables (arrays, collections) automatically. Passing an array of objects to Cast::from() returns an array of mapped objects.

$orders = $repository->findAll(); // array<Order>

// Returns array<OrderDto>
$dtos = Cast::from($orders)->to(OrderDto::class);

Requirements

  • PHP 8.2 or higher

License

MIT