guennichi/mapper

A lightweight library to map array data to PHP immutable objects

2.1.2 2024-01-15 13:00 UTC

This package is auto-updated.

Last update: 2024-11-15 14:53:21 UTC


README

A lightweight library to map array data into PHP immutable objects, collections and strongly typed arrays via constructors.

Benchmark

Check benchmark/ directory for more details about the implementation.

Installation

composer require guennichi/mapper

Usage

use Guennichi\Collection\Collection;

final class Person
{
    public function __construct(public readonly string $name) {}
}

/**
 * @extends Collection<Person>
 */
final class PersonCollection extends Collection
{
    public function __construct(Person ...$elements)
    {
        parent::__construct(...$elements);
    }
}

$input = [
    ['name' => 'Person1'],
    ['name' => 'Person2'],
    ['name' => 'Person3'],
];

$mapper = new Guennichi\Mapper\Mapper(/** dependencies */)

$output = $mapper->map($input, PersonCollection::class);
// Result instance of PersonCollection(Person{"name": "Person1"}, Person{"name": "Person2"}, Person{"name": "Person3"})

Dedication

Special thanks to my colleague @Gabriel Ostrolucký for his support and advices to make this happen.