From 0fb4ac3547ffcca031974103ae43e12bcd877781 Mon Sep 17 00:00:00 2001 From: Wendell Adriel Date: Mon, 15 Jul 2024 11:34:41 +0100 Subject: [PATCH] Fix issue with toArray --- src/SimpleDTO.php | 4 ++++ tests/Unit/SimpleDTOTest.php | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/SimpleDTO.php b/src/SimpleDTO.php index b36332f..b44c264 100644 --- a/src/SimpleDTO.php +++ b/src/SimpleDTO.php @@ -401,6 +401,10 @@ private function mapDTOData(array $mapping, array $data): array ? $mapping[$key] : $key; + if (isset($this->{$key}) && $value !== $this->{$key}) { + $value = $this->{$key}; + } + $mappedData[$property] = $this->isArrayable($value) ? $this->formatArrayableValue($value) : $value; diff --git a/tests/Unit/SimpleDTOTest.php b/tests/Unit/SimpleDTOTest.php index 42620f4..7266c4d 100644 --- a/tests/Unit/SimpleDTOTest.php +++ b/tests/Unit/SimpleDTOTest.php @@ -8,6 +8,7 @@ use Illuminate\Http\Request; use WendellAdriel\ValidatedDTO\Exceptions\InvalidJsonException; use WendellAdriel\ValidatedDTO\SimpleDTO; +use WendellAdriel\ValidatedDTO\Tests\Datasets\AttributesDTO; use WendellAdriel\ValidatedDTO\Tests\Datasets\CallableCastingDTOInstance; use WendellAdriel\ValidatedDTO\Tests\Datasets\SimpleDTOInstance; use WendellAdriel\ValidatedDTO\Tests\Datasets\SimpleMapBeforeExportDTO; @@ -301,3 +302,15 @@ public function __invoke() {} ->and($dto->age) ->toBe(30); }); + +it('checks that update for property reflects while converting DTO', function () { + $dto = AttributesDTO::fromArray([ + 'age' => 18, + 'doc' => 'test', + ]); + + $dto->age = 20; + + expect($dto->age)->toBe(20) + ->and($dto->toArray())->toBe(['age' => 20, 'doc' => 'test']); +});