Skip to content

Commit

Permalink
Fix issue of missing properties when transforming DTO
Browse files Browse the repository at this point in the history
  • Loading branch information
WendellAdriel committed Nov 11, 2024
1 parent 17bd33c commit ffa3e7d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/SimpleDTO.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 22 additions & 3 deletions tests/Unit/ValidatedDTOTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand All @@ -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 () {
Expand All @@ -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 () {
Expand Down Expand Up @@ -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 () {
Expand Down

0 comments on commit ffa3e7d

Please sign in to comment.