PHP code example of alexpts / php-data-transformer2

1. Go to this page and download the library: Download alexpts/php-data-transformer2 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/ */

    

alexpts / php-data-transformer2 example snippets


use PTS\DataTransformer\DataTransformer;

$dataTransformer = new DataTransformer;
$dataTransformer->getMapsManager()->setMapDir(UserModel::class, __DIR__ . '/data');

$model = $dataTransformer->toModel(UserModel::class, [
    'id' => 1,
    'creAt' => new DateTime,
    'name' => 'Alex',
    'active' => 1,
]);

$dto = $dataTransformer->toDTO($model, 'dto');
$dtoForDb = $dataTransformer->toDTO($model, 'db');

$shortFormatDto = $dataTransformer->toDTO($model, 'short.dto');

$shortFormatDto = $dataTransformer->toDTO($model, 'dto', [
     'excludeFields' => ['password']
]);

$mapName = 'dto';
$excludedFields = ['name'];
$dtoCollection = $dataTransformer->toDtoCollection($models, $mapName);

// map file deepDto.php
return [
    'id' => [],
    'creAt' => [],
    'name' => [],
    'login' => [],
    'active' => [
        'pipe-populate' => ['boolval'],
        'pipe-extract' => ['boolval'],
    ],
    'email' => [
        'pipe-populate' => [ // any callable
            'strval',
            'strtolower',
         ]
    ],
    'refModel' => [
        'ref' => [
            'model' => UserModel::class,
            'map' => 'dto'
        ]
    ],
    'refModels' => [
        'ref' => [
            'model' => UserModel::class,
            'map' => 'dto',
            'collection' => true
        ]
    ],
];

// code file
$model = $dataTransformer->toModel(UserModel::class, [
    'id' => 1,
    'creAt' => new DateTime,
    'name' => 'Alex',
    'active' => 1,
    'refModel' => [
        'id' => 2,
        'name' => 'refModel',
    ]
], 'deepDto');

$model2 = $dataTransformer->toModel(UserModel::class, [
    'id' => 1,
    'creAt' => new DateTime,
    'name' => 'Alex',
    'active' => 1,
    'refModels' => [ // collection ref models
        [
            'id' => 2,
            'name' => 'refModel',
        ],
        [
            'id' => 2,
            'name' => 'refModel',
        ]
    ]
], 'deepDto');


/**
 * @var MapsManager $this
 */

use PTS\DataTransformer\MapsManager;

$encrypter = $this->getContainer()->get('encrypter');

return [
    'id' => [],
    'creAt' => [],
    'name' => [],
    'password' => [
        'pipe-populate' => [
            'strtolower',
            function(string $openPassword) use($encrypter) {
                return $encrypter->encrypt($openPassword);
            },
        ],
        'pipe-extract' => [
            function(string $ePassword) use($encrypter) {
                return $encrypter->decrypt($ePassword);
            },
            'strtolower'
        ],
    ]
];