jolicode / automapper

:rocket: Very FAST :rocket: PHP AutoMapper with on the fly code generation
https://automapper.jolicode.com/
MIT License
154 stars 15 forks source link

Is it possible to map a property that doesn't exist in the source ? #163

Closed jeremyVignelles closed 5 months ago

jeremyVignelles commented 5 months ago

I have a use case that can be summarized like this:

class ARequest {
   public string $value;
}

class BRequest {
   public string $value;
}

class Entity {
   public string $type;
   public string $value;
}

Both ARequest and BRequest can be mapped to my Entity, but I want $type to be either 'A' or 'B'.

Is there a way to automatically fill $type ?

Something like:

#[MapFrom(source: ARequest::class, constant_value: 'A')]
#[MapFrom(source: BRequest::class, constant_value: 'B')]
public string $type;
Korbeil commented 5 months ago

Hey @jeremyVignelles and thanks for your issue.

For your case I would have used a transformer as following:

#[MapFrom(source: ARequest::class, transformer: "'A'")]
#[MapFrom(source: BRequest::class, tranformer: "'B'")]
public string $type;

Please note that I used both " and ' because you need to put the ExpressionLanguage parsed content in a string and you need tell ExpressionLanguage that you want to return a string (thanks to ' in my example).

Does that fit your use-case ?

jeremyVignelles commented 5 months ago

Sounds good, thanks for your quick reply.

I didn't test this as our code base is not ready yet, so I'm going to close this issue and reopen later if more help is needed.