Skip to content

Commit

Permalink
Merge pull request #94 from WendellAdriel/hotfix/transform-issue
Browse files Browse the repository at this point in the history
Fix issue of missing properties when transforming DTO
  • Loading branch information
WendellAdriel authored Nov 11, 2024
2 parents 17bd33c + ffa3e7d commit 07d95d7
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 07d95d7

Please sign in to comment.