type-lang/mapper

Library for mapping variable types to other types

This package is auto-updated.

Last update: 2024-10-24 19:42:17 UTC


README

PHP 8.1+ Latest Stable Version Latest Unstable Version License MIT

The best PHP mapper you've ever seen =)

You can see some examples here:

Full documentation in progress...

Installation

Mapper package is available as Composer repository and can be installed using the following command in a root of your project:

composer require type-lang/mapper

Benchmarks

Results here like this.

Sample: An object that contains a collection of objects, which contains another collection of objects.

ExampleObject{
    name: string,
    items: list<ExampleObject>
}

Denormalization

Denormalization: Transformation from raw payload (array) to concrete object.

Normalization

Normalization: Transformation from object to raw payload (array).

Quick Start

use TypeLang\Mapper\Mapping\MapType;

class ExampleObject
{
    public function __construct(
        #[MapType('list<non-empty-string>')]
        public readonly array $names,
    ) {}
}

$mapper = new \TypeLang\Mapper\Mapper();

$result = $mapper->normalize(
    new ExampleObject(['Example'])
);
// Expected Result:
//
// array:1 [
//   "names" => array:1 [
//     0 => "Example"
//   ]
// ]


$result = $mapper->denormalize([
    'names' => ['first', 'second']
], ExampleObject::class);
// Expected Result:
//
// ExampleObject {#324
//   +names: array:2 [
//     0 => "first"
//     1 => "second"
//   ]
// }


$result = $mapper->denormalize([
    'names' => ['first', 'second', ''],
], ExampleObject::class);
// Expected Result:
//
// InvalidFieldTypeValueException: Passed value of field "names" must be of type
//   list<non-empty-string>, but array(3)["first", "second", ""] given at $.names[2]