Closed praad closed 3 years ago
If I understand correctly you have the following situation:
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.
Thanks this was a glue $config->getOptions()->ignoreNullProperties();
Given $object1 and $object2 with same type. How can I update $object1 attributes with the not null values of $object2. Is it possible?