From 0342ececc526511d624139b61cc4c32efcffbaa1 Mon Sep 17 00:00:00 2001 From: circle33 Date: Wed, 8 Nov 2023 20:21:08 +0800 Subject: [PATCH 1/2] Fix issue where non set optional values were transformed --- src/Transformers/DataTransformer.php | 4 ++++ tests/ValidationTest.php | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/Transformers/DataTransformer.php b/src/Transformers/DataTransformer.php index bddb4de2a..a10b2f558 100644 --- a/src/Transformers/DataTransformer.php +++ b/src/Transformers/DataTransformer.php @@ -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; } diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index 9917cf620..0a06ba9c6 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -2379,3 +2379,14 @@ 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(['property' => null])->toArray())->toBe(['property' => null]); + expect($dataClass::from(['property' => []])->toArray())->toBe(['property' => []]); + expect($dataClass::validateAndCreate([])->toArray())->toBe([]); +}); From 9452f08dbe85efc4cc7d9312503ac22bb67508a5 Mon Sep 17 00:00:00 2001 From: circle33 Date: Wed, 8 Nov 2023 23:00:48 +0800 Subject: [PATCH 2/2] test: add more test case --- tests/ValidationTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index 0a06ba9c6..20180e222 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -2386,6 +2386,7 @@ public static function rules(ValidationContext $context): array }; 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([]);