mark-gerarts / automapper-plus

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

Update object without creating new #65

Closed praad closed 3 years ago

praad commented 3 years ago

Given $object1 and $object2 with same type. How can I update $object1 attributes with the not null values of $object2. Is it possible?

mark-gerarts commented 3 years ago

If I understand correctly you have the following situation:

  1. Object A and B are of the same type
  2. You want to map the values of A to the existing object B
  3. You want to ignore null values when doing so

If this is correct, the following snippet should help:

class SomeClass
{
    public string $name;

    public ?string $nullProperty;

    public function __construct(string $name, ?string $nullProperty = null)
    {
        $this->name = $name;
        $this->nullProperty = $nullProperty;
    }
}

$a = new SomeClass('Object A', null);
$b = new SomeClass('Object B', 'Im not null');

$config = new AutoMapperConfig();
$config->getOptions()->ignoreNullProperties(); // 3. Ignore null values of the source object.
$config->registerMapping(SomeClass::class, SomeClass::class); // 1. Register a mapping between the same type.
$mapper = new AutoMapper($config);

var_dump($b);
$mapper->mapToObject($a, $b); // 2. mapToObject updates object $b instead of creating a new one.
var_dump($b);

This outputs:

object(SomeClass)#2 (2) {
  ["name"]=>
  string(8) "Object B"
  ["nullProperty"]=>
  string(11) "Im not null"
}
object(SomeClass)#2 (2) {
  ["name"]=>
  string(8) "Object A"
  ["nullProperty"]=>
  string(11) "Im not null"
}

If I misunderstood, please let me know.

praad commented 3 years ago

Thanks this was a glue $config->getOptions()->ignoreNullProperties();