Skip to content

Commit

Permalink
Fix issue where non set optional values were transformed
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenvanassche committed Oct 12, 2023
1 parent 8787289 commit 3b63875
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
6 changes: 5 additions & 1 deletion 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 && ! isset($data->{$name})) {
continue;
}

if (! $this->shouldIncludeProperty($name, $data->{$name}, $trees)) {
continue;
}
Expand Down Expand Up @@ -234,7 +238,7 @@ protected function resolvePropertyValue(
};

if ($value instanceof TransformableData && $this->transformValues) {
return $value->transform($this->transformValues, $wrapExecutionType, $this->mapPropertyNames, );
return $value->transform($this->transformValues, $wrapExecutionType, $this->mapPropertyNames,);
}

return $value;
Expand Down
16 changes: 12 additions & 4 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@
use Illuminate\Validation\Rules\In as LaravelIn;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;

use function Pest\Laravel\mock;
use function PHPUnit\Framework\assertFalse;

use Spatie\LaravelData\Attributes\DataCollectionOf;
use Spatie\LaravelData\Attributes\MapInputName;
use Spatie\LaravelData\Attributes\MapName;
Expand Down Expand Up @@ -69,6 +65,8 @@
use Spatie\LaravelData\Tests\Fakes\Support\FakeInjectable;
use Spatie\LaravelData\Tests\Fakes\ValidationAttributes\PassThroughCustomValidationAttribute;
use Spatie\LaravelData\Tests\TestSupport\DataValidationAsserter;
use function Pest\Laravel\mock;
use function PHPUnit\Framework\assertFalse;

it('can validate a string', function () {
$dataClass = new class () extends Data {
Expand Down Expand Up @@ -2379,3 +2377,13 @@ 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('will not transform non set optional properties ', function () {
$dataClass = new class extends Data {
public array|Optional $optional;
};

expect($dataClass::from([])->toArray())->toBeEmpty();
expect($dataClass::from()->toArray())->toBeEmpty();
expect((new ($dataClass::class))->toArray())->toBeEmpty();
});

0 comments on commit 3b63875

Please sign in to comment.