A PHP library to map associative arrays to typed DTOs using attributes.
Install from Packagist:
composer require rjds/php-dtoRequirements:
- PHP 8.1 or higher
DtoMapper converts associative arrays to typed constructor-based DTOs.
use Rjds\PhpDto\Attribute\ArrayOf;
use Rjds\PhpDto\Attribute\CastTo;
use Rjds\PhpDto\Attribute\MapFrom;
use Rjds\PhpDto\DtoMapper;
final class TagDto
{
public function __construct(
public readonly string $name,
public readonly string $url,
) {
}
}
final class ArtistDto
{
/** @param list<TagDto> $tags */
public function __construct(
public readonly string $name,
#[MapFrom('stats.play_count')]
#[CastTo('int')]
public readonly int $playCount,
#[ArrayOf(TagDto::class)]
public readonly array $tags,
) {
}
}
$mapper = new DtoMapper();
$artist = $mapper->map([
'name' => 'Arctic Monkeys',
'stats' => ['play_count' => '150316'],
'tags' => [
['name' => 'rock', 'url' => 'https://www.last.fm/tag/rock'],
['name' => 'indie', 'url' => 'https://www.last.fm/tag/indie'],
],
], ArtistDto::class);
echo $artist->playCount; // 150316 (int)
echo $artist->tags[0]->name; // rock- Zero-boilerplate name-based mapping for constructor arguments
#[MapFrom]support for renamed and nested keys using dot notation#[CastTo]support forint,float,string,bool, anddatetime#[ArrayOf]support for mapping nested DTO collections- Constructor default values respected when source keys are missing
Map a parameter from a different key, including nested paths:
#[MapFrom('profile.first_name')]
public readonly string $firstNameCast scalar string input into strongly typed DTO fields:
#[CastTo('datetime')]
public readonly \DateTimeImmutable $registeredAtMap list entries to nested DTO instances:
#[ArrayOf(TagDto::class)]
public readonly array $tagscomposer install
php vendor/bin/grumphp runRun mutation testing:
php vendor/bin/infection --threads=4Contributions are welcome. See CONTRIBUTING.md for branch strategy, commit conventions, and PR workflow.
This project is released under the MIT License. See LICENSE for details and CHANGELOG.md for release history.