PHP code example of emulgeator / array-to-class-mapper

1. Go to this page and download the library: Download emulgeator/array-to-class-mapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

emulgeator / array-to-class-mapper example snippets


use Emul\ArrayToClassMapper\MapperFactory;

class DTO
{
    private int $id;

    private float $value;

    public function __construct() {
        // Constructor wont be called
    }
}

$arrayToMap = [
    'id' => '1',
    'value' => '1.2'
];

$mapper = (new MapperFactory())->getMapper();

/** @var DTO $dto */
$dto = $mapper->map($arrayToMap, DTO::class);

use Emul\ArrayToClassMapper\MapperFactory;

    private string $value;
}

class DTO
{
    private InnerDTO $inner;
}

$arrayToMap = [
    'inner' => [
        'key'   => 'first_key',
        'value' => 'value'
    ]
];

$mapper = (new MapperFactory())->getMapper();

/** @var DTO $dto */
$dto = $mapper->map($arrayToMap, DTO::class);

use Emul\ArrayToClassMapper\MapperFactory;

    private string $value;
}

class DTO
{
    private int $id;

    /** @var InnerDTO[] */
    private array $inner = [];
}

$arrayToMap = [
    'id' => 1,
    'inner' => [
        [
            'key'   => 'first_key',
            'value' => 'value'
        ],
        [
            'key'   => 'second_key',
            'value' => 'value'
        ],
    ]
];

$mapper = (new MapperFactory())->getMapper();

/** @var DTO $dto */
$dto = $mapper->map($arrayToMap, DTO::class);

use Carbon\Carbon;
use Carbon\CarbonInterface;
use Emul\ArrayToClassMapper\MapperFactory;

 __construct(string $keyPrefix, string $key, string $value)
    {
        $this->key   = $keyPrefix . $key;
        $this->value = $value;
    }
}

class DTO
{
    private int $id;

    /** @var InnerDTO[] */
    private array $values;
}

$arrayToMap = [
    'id'        => 1,
    'values' => [
        [
            'key' => 'first',
            'value' => '1'
        ],
    ],
];

$mapper = (new MapperFactory())->getMapper();

$innerDTOMapper = \Closure::fromCallable(function (array $data) {
    return new InnerDTO('prefix_', $data['key'], $data['value']);
});

$mapper->addCustomMapper(InnerDTO::class, $innerDTOMapper);
/** @var DTO $dto */
$dto = $mapper->map($arrayToMap, DTO::class);

/** @var Value[] */
private array $values = [];

/** @var \NameSpace\Value[] */
private array $values = [];