From ffa3e7d9122446d5fa575da8474ec3ae80dbe1e9 Mon Sep 17 00:00:00 2001 From: Wendell Adriel Date: Mon, 11 Nov 2024 12:06:17 +0000 Subject: [PATCH] Fix issue of missing properties when transforming DTO --- src/SimpleDTO.php | 9 ++++++++- tests/Unit/ValidatedDTOTest.php | 25 ++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/SimpleDTO.php b/src/SimpleDTO.php index 8eef3af..28ec099 100644 --- a/src/SimpleDTO.php +++ b/src/SimpleDTO.php @@ -312,7 +312,14 @@ protected function buildDataForExport(): array ...$this->dtoMapTransform, ]; - return $this->mapDTOData($mapping, $this->validatedData); + $data = $this->validatedData; + foreach ($this->getAcceptedProperties() as $property) { + if (! array_key_exists($property, $data) && isset($this->{$property})) { + $data[$property] = $this->{$property}; + } + } + + return $this->mapDTOData($mapping, $data); } protected function buildDataForValidation(array $data): array diff --git a/tests/Unit/ValidatedDTOTest.php b/tests/Unit/ValidatedDTOTest.php index d78f1f4..58d2398 100644 --- a/tests/Unit/ValidatedDTOTest.php +++ b/tests/Unit/ValidatedDTOTest.php @@ -215,6 +215,10 @@ public function __invoke() {} expect($validatedDTO)->toArray() ->toBe($dataStructure); + + $validatedDTO->age = 20; + expect($validatedDTO)->toArray() + ->toBe([...$dataStructure, 'age' => 20]); }); it('validates that the ValidatedDTO can be converted into a JSON string', function () { @@ -223,6 +227,10 @@ public function __invoke() {} expect($validatedDTO)->toJson() ->toBe(json_encode($dataStructure)); + + $validatedDTO->age = 20; + expect($validatedDTO)->toJson() + ->toBe(json_encode([...$dataStructure, 'age' => 20])); }); it('validates that the ValidatedDTO can be converted into a pretty JSON string', function () { @@ -231,6 +239,10 @@ public function __invoke() {} expect($validatedDTO)->toPrettyJson() ->toBe(json_encode($dataStructure, JSON_PRETTY_PRINT)); + + $validatedDTO->age = 20; + expect($validatedDTO)->toPrettyJson() + ->toBe(json_encode([...$dataStructure, 'age' => 20], JSON_PRETTY_PRINT)); }); it('validates that the ValidatedDTO with nested data can be converted into an array', function () { @@ -361,15 +373,22 @@ public function __invoke() {} $model = new class() extends Model { - protected $fillable = ['name']; + protected $fillable = ['name', 'age']; }; - $model_instance = $validatedDTO->toModel($model::class); + $modelInstance = $validatedDTO->toModel($model::class); - expect($model_instance) + expect($modelInstance) ->toBeInstanceOf(Model::class) ->toArray() ->toBe(['name' => $this->subject_name]); + + $validatedDTO->age = 20; + $modelInstance = $validatedDTO->toModel($model::class); + expect($modelInstance) + ->toBeInstanceOf(Model::class) + ->toArray() + ->toBe(['name' => $this->subject_name, 'age' => 20]); }); it('maps data before validation', function () {