Skip to content

Commit

Permalink
Merge pull request #602 from rust17/main
Browse files Browse the repository at this point in the history
Fix issue where non set optional values were transformed
  • Loading branch information
rubenvanassche authored Dec 1, 2023
2 parents 02752fc + 9452f08 commit f61000f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Transformers/DataTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ protected function resolvePayload(TransformableData $data): array

$name = $property->name;

if ($property->type->isOptional && ! array_key_exists($name, get_object_vars($data))) {
continue;
}

if (! $this->shouldIncludeProperty($name, $data->{$name}, $trees)) {
continue;
}
Expand Down
12 changes: 12 additions & 0 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2379,3 +2379,15 @@ public static function rules(ValidationContext $context): array
->assertOk(['success' => true, 'id' => 1])
->assertErrors(['success' => true]);
})->skip('V4: The rule inferrers need to be rewritten/removed for this, we need to first add attribute rules and then decide require stuff');

it('can validate an optional but nonexists attribute', function () {
$dataClass = new class () extends Data {
public array|null|Optional $property;
};

expect($dataClass::from()->toArray())->toBe([]);
expect($dataClass::from([])->toArray())->toBe([]);
expect($dataClass::from(['property' => null])->toArray())->toBe(['property' => null]);
expect($dataClass::from(['property' => []])->toArray())->toBe(['property' => []]);
expect($dataClass::validateAndCreate([])->toArray())->toBe([]);
});

0 comments on commit f61000f

Please sign in to comment.