automapper icon indicating copy to clipboard operation
automapper copied to clipboard

Flattening

Open Korbeil opened this issue 2 years ago • 3 comments

Inspired from https://docs.automapper.org/en/stable/Flattening.html

The idea is to makes simpler DTO compared to your source entities (or whatever your source is). Let's do a quick example:

// source
class User
{
  public string $email;
}

class Order
{
  public string $reference;
  public User $customer;
}

// target
class OrderDTO
{
  public string $reference;
  public string $customerEmail;
}

$customer = new User();
$customer->email = '[email protected]';
$source = new Order();
$source->reference = 'FAC9123';
$source->customer = $customer;

dump($autoMapper->map($source, OrderDTO::class));

// Will output:
//
// OrderDTO {#14 🔽
//  +reference: "FAC9123"
//  +customerEmail: "[email protected]"
// }

Idea is to flatten the objects so they can be mapped to a property with a name matching their path, in this example we have "Order -> customer (User) -> email" that is flatten to "Order -> customerEmail"

Korbeil avatar Oct 23 '23 12:10 Korbeil

I think this can be done with transformer and expression language now ?

Like :

class Order
{
  public string $reference;
  #[MapTo(OrderDTO::class, name: 'customerEmail', transformer: 'source.customer.email')]
  public User $customer;
}

Do we want to add more than that ? (I think it will be pretty complicated, so i would say no)

joelwurtz avatar Mar 28 '24 15:03 joelwurtz

I would like it to be some kind of configuration and it will do flattening automatically without the need to make attributes.

Korbeil avatar Mar 31 '24 07:03 Korbeil

Making the customer->email map to customerEmail automatically feels too magical for me.

I would prefer the ability to do it by hand, via attributes.

Also, the transformer solution is only working when reading a nested property, not the other way around.

In that example there is no way to map OrderDTO->customerEmail to Order->User->email.

damienalexandre avatar Jan 17 '25 21:01 damienalexandre