Skip to content

Commit c620967

Browse files
Fix an issue where required rules could not be combined with optional (#844)
1 parent cf86d7a commit c620967

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed

src/RuleInferrers/AttributesRuleInferrer.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Spatie\LaravelData\RuleInferrers;
44

55
use Spatie\LaravelData\Attributes\Validation\Present;
6+
use Spatie\LaravelData\Attributes\Validation\Sometimes;
67
use Spatie\LaravelData\Support\DataProperty;
78
use Spatie\LaravelData\Support\Validation\PropertyRules;
89
use Spatie\LaravelData\Support\Validation\RequiringRule;
@@ -29,6 +30,10 @@ public function handle(
2930
$rules->removeType(RequiringRule::class);
3031
}
3132

33+
if ($rule instanceof RequiringRule && $rules->hasType(Sometimes::class)) {
34+
$rules->removeType(Sometimes::class);
35+
}
36+
3237
$rules->add(
3338
...$this->rulesDenormalizer->execute($rule)
3439
);

tests/ValidationTest.php

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,18 +1082,26 @@ class CollectionClassC extends Data
10821082
->assertRules(
10831083
[
10841084
'someData' => [
1085-
'sometimes',
10861085
'array',
10871086
'required_without:someOtherData',
10881087
],
10891088
'someOtherData' => [
1090-
'sometimes',
10911089
'array',
10921090
'required_without:someData',
10931091
],
10941092
],
1095-
[]
1096-
);
1093+
)
1094+
->assertOk([
1095+
'someData' => [["string" => "Hello World"]],
1096+
])
1097+
->assertOk([
1098+
'someOtherData' => [["string" => "Hello World"]],
1099+
])
1100+
->assertOk([
1101+
'someData' => [["string" => "Hello World"]],
1102+
'someOtherData' => [["string" => "Hello World"]],
1103+
])
1104+
->assertErrors([]);
10971105
});
10981106

10991107
it('supports required without validation for nullable collections', function () {
@@ -2429,3 +2437,28 @@ public function __construct(
24292437
'some_property' => 1,
24302438
]);
24312439
})->skip('Validation problem, fix in v5');
2440+
2441+
it('will remove a sometimes rule generated by an Optional type when manually requiring something', function () {
2442+
$dataClass = new class () extends Data {
2443+
#[RequiredWith('otherProperty')]
2444+
public string|Optional $property;
2445+
2446+
public string|null $otherProperty;
2447+
};
2448+
2449+
DataValidationAsserter::for($dataClass)
2450+
->assertRules([
2451+
'property' => ['string', 'required_with:otherProperty'],
2452+
'otherProperty' => ['nullable', 'string'],
2453+
], ['property' => 'Hello World', 'otherProperty' => 'Hello World'])
2454+
->assertOk([
2455+
'property' => 'Hello World',
2456+
'otherProperty' => 'Hello World',
2457+
])
2458+
->assertOk([
2459+
'otherProperty' => null,
2460+
])
2461+
->assertErrors([
2462+
'otherProperty' => 'Hello World',
2463+
]);
2464+
});

0 commit comments

Comments
 (0)