Allows mapping data between different formats, such as JSON, arrays, and DTOs, providing flexibility in transforming and serializing information.
composer require tiny-blocks/mapper
The examples demonstrate how to create objects from iterables, map objects to arrays, and convert objects to JSON.
First, define your classes using the ObjectMapper
interface and ObjectMappability
trait:
<?php
declare(strict_types=1);
namespace Example;
use TinyBlocks\Mapper\ObjectMappability;
use TinyBlocks\Mapper\ObjectMapper;
final readonly class ShippingAddress implements ObjectMapper
{
use ObjectMappability;
public function __construct(
private string $city,
private ShippingState $state,
private string $street,
private int $number,
private ShippingCountry $country
) {
}
}
Next, define a collection class implementing IterableMapper
:
<?php
declare(strict_types=1);
namespace Example;
use TinyBlocks\Collection\Collection;
use TinyBlocks\Mapper\IterableMappability;
use TinyBlocks\Mapper\IterableMapper;
final class ShippingAddresses extends Collection implements IterableMapper
{
use IterableMappability;
public function getType(): string
{
return ShippingAddress::class;
}
}
Finally, create a class that uses the collection:
<?php
declare(strict_types=1);
namespace Example;
use TinyBlocks\Mapper\ObjectMappability;
use TinyBlocks\Mapper\ObjectMapper;
final readonly class Shipping implements ObjectMapper
{
use ObjectMappability;
public function __construct(public int $id, public ShippingAddresses $addresses)
{
}
}
Now you can map data into a Shipping
object using fromIterable
:
<?php
use Example\Shipping;
$shipping = Shipping::fromIterable(iterable: [
'id' => PHP_INT_MAX,
'addresses' => [
[
'city' => 'New York',
'state' => 'NY',
'street' => '5th Avenue',
'number' => 717,
'country' => 'US'
]
]
]);
Once the object is created, you can easily convert it into an array representation.
$shipping->toArray();
This will output the following array:
[
'id' => 9223372036854775807,
'addresses' => [
[
'city' => 'New York',
'state' => 'NY',
'street' => '5th Avenue',
'number' => 717,
'country' => 'US'
]
]
]
Similarly, you can convert the object into a JSON representation.
$shipping->toJson();
This will produce the following JSON:
{
"id": 9223372036854775807,
"addresses": [
{
"city": "New York",
"state": "NY",
"street": "5th Avenue",
"number": 717,
"country": "US"
}
]
}
Mapper is licensed under MIT.
Please follow the contributing guidelines to contribute to the project.