mark-gerarts / automapper-plus

An AutoMapper for PHP
MIT License
551 stars 30 forks source link

Map to array/list of objects #50

Closed ivoba closed 4 years ago

ivoba commented 4 years ago

Is it possible to map to a typed list resp. an array of objects?

Imagine a class like this:

class MyObject{
    /**
     * @var Thing[]
     */
    private $things;

    /**
     * @return Thing[]
     */
    public function getThings(): array
    {
        return $this->things;
    }

    /**
     * @param Thing[] $things
     * @return MyObject
     */
    public function setThings(array $things): MyObject
    {
        $this->things = $things;

        return $this;
    }

}

When mapping from an array i did this:

$config->registerMapping(DataType::ARRAY, Thing::class);
$config->registerMapping(DataType::ARRAY, MyObject::class)
       ->forMember(
           'things',
           function (array $things, AutoMapperInterface $mapper) {
               $ret = [];
               foreach ($things['things'] as $thing) {
                   $ret[] = $mapper->map($thing, Thing::class);
               }
               return $ret;
           }
       );

I guess it would be convenient to have a operation for this custom callback to map to a list. Like: Operation::mapArrayToArray(Things::class);

mark-gerarts commented 4 years ago

Hi @ivoba. I might be understanding your use case wrong, but I think mapTo does what you want. Your config could look like this:

$config->registerMapping(DataType::ARRAY, Thing::class);
$config->registerMapping(DataType::ARRAY, MyObject::class)
    ->forMember('things', Operation::mapTo(Thing::class));

This works because mapTo supports both single and multiple values. Please let me know if this solved your problem!

ivoba commented 4 years ago

@mark-gerarts yes you are right, this works as you describe. Probably i had some wrong input data. Thank you!