data-transfer-object
data-transfer-object copied to clipboard
Unexpected behavior on clone and MapTo
Hey,
I want to report an unexpected behavior/ bug when using clone and MapTo.
Here is an example:
class ExampleData extends DataTransferObject
{
#[MapTo('account_id')]
public ?int $account;
#[CastWith(CarbonImmutableCaster::class), MapTo('expires_at')]
public ?CarbonImmutable $expiresAt;
}
Reproduce the problem:
$o = new ExampleData(
account: 1,
expiresAt: '2020-01-01 12:00:00'
);
$nO = $o->clone(account: 2); // I would expect $nO to have account 2 with same expiresAt
$nO->toArray() // [account: 2, expires_at: null]
This happens because of how clone/ toArray works:
public function clone(...$args): static
{
return new static(...array_merge($this->toArray(), $args));
}
The code above does something like:
return new static(...array_merge([
'account_id' => 1,
'expires_at': '2020-01-01 12:00:00'
], [
'account' => 2
]);
And this is where the problem comes in. The property name is expiresAt so expires_at is not matched and instead dropped. Only account works, as it is specified correctly.
This maybe could be avoided with a MapFrom I guess, but I expect it to work without.
Could we potentially change/fix this behavior?