Autotransformer is a little tool which does basic DTO to entity transforming and vise versa.
composer require tibisoft/autotransformer
Without any extra configuration the transformer will loop over the properties of the target class/object and will try to find a equally named property in the source.
class User {
public function __construct(
private string $email,
private string $plainPassword,
private int $age,
) {
}
}
class UserDTO {
public function __construct(
private string $email,
private int $age,
) {
}
}
$user = new User('[email protected]', 'someSecretPassword', 25);
$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);
//output:
object(UserDTO)#8 (2) {
["email":"UserDTO":private]=>
string(17) "[email protected]"
["age":"UserDTO":private]=>
int(25)
}
If the default transforming process is not enough you can add attributes to the target object/class and customise the output.
class User {
public function __construct(
private string $email,
private string $plainPassword,
private int $age,
) {
}
}
class UserDTO {
public function __construct(
private string $email,
#[\Tibisoft\AutoTransformer\Attribute\Synonyms(['age'])]
private int $yearsLive,
) {
}
}
$user = new User('[email protected]', 'someSecretPassword', 25);
$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);
//output:
object(UserDTO)#8 (2) {
["email":"UserDTO":private]=>
string(17) "[email protected]"
["yearsLive":"UserDTO":private]=>
int(25)
}
class User {
public function __construct(
private string $email,
private array $comments,
) {
}
}
class UserDTO {
public function __construct(
private string $email,
#[\Tibisoft\AutoTransformer\Attribute\Count]
private int $comments,
) {
}
}
$user = new User('[email protected]', ['Comment #1', 'Comment #2', 'Comment #3', 'Comment #4']);
$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$userDTO = $transformer->transform($user, UserDTO::class);
//output:
object(UserDTO)#8 (2) {
["email":"UserDTO":private]=>
string(17) "[email protected]"
["comments":"UserDTO":private]=>
int(4)
}
class InArrayClass
{
public function __construct(
public array $roles = [],
) {
}
}
class InArrayDTO
{
public function __construct(
#[\Tibisoft\AutoTransformer\Attribute\InArray(property: 'roles', value: 'ROLE_TEAMLEADER')]
public bool $isTeamleader,
) {
}
}
$object = new InArrayClass(['ROLE_USER', 'ROLE_TEAMLEADER']);
$transformer = new \Tibisoft\AutoTransformer\AutoTransformer();
$inArrayDTO = $transformer->transform($object, InArrayDTO::class);
//output:
object(InArrayDTO)#8 (1) {
["isTeamleader"]=>
bool(true)
}