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

Split source array into differents target attributes #113

Closed orangevinz closed 6 months ago

orangevinz commented 7 months ago

Is it possible to transform an object/DTO to multiple target attributes ?

Source:

{
    "name": "John DOE",
    "job": {
        "company": "MyCompany",
        "title": "I am a developer" 
    }
}
// MainDTO
final class ProfileDTO
{
   public string $name;

   #[MapTo(name: '????', transformer: JobTransformer::class)]
   #[ApiProperty(description: 'Job information.')]
   public ?JobDTO $job = null;
}
// Sub DTO
final class JobDTO
{
    #[ApiProperty(description: 'Company name.')]
    public ?string $company = null;

    public ?string $title = null;
}
// My entity
class Profile
{
   #[ORM\Column(length: 255, nullable: true)]
    private ?string $name = null;   

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $jobTitle = null;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $jobCompany = null;
}
class JobTransformer implements PropertyTransformerInterface
{
    /**
     * @param JobDTO $value
     */
    public function transform(mixed $value, array|object $source, array $context): mixed
    {
        // ???
    }
}
joelwurtz commented 6 months ago

You could do something like this :

final class ProfileDTO
{
   public string $name;

   #[MapTo(target: Profile::class, name: 'jobTitle', transformer: 'source.job ? source.job.title : null')]
   #[MapTo(target: Profile::class, name: 'jobCompany', transformer: 'source.job ? source.job.company : null')]
   #[ApiProperty(description: 'Job information.')]
   public ?JobDTO $job = null;
}
orangevinz commented 6 months ago

Ok got it. Thanks