Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add require_rule_for_booleans option #813

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config/data.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@
Spatie\LaravelData\RuleInferrers\AttributesRuleInferrer::class,
],

/**
* By default, boolean attributes that are non-optional, non-nullable, and have no default value are not required during validation.
*/
'require_rule_for_booleans' => false,

/**
* Normalizers return an array representation of the payload, or null if
* it cannot normalize the payload. The normalizers below are used for
Expand Down
4 changes: 3 additions & 1 deletion src/RuleInferrers/BuiltInTypesRuleInferrer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public function handle(
}

if ($property->type->type->acceptsType('bool')) {
$rules->removeType(RequiringRule::class);
if (! config('data.require_rule_for_booleans')) {
$rules->removeType(RequiringRule::class);
}

$rules->add(new BooleanType());
}
Expand Down
16 changes: 13 additions & 3 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,27 @@
]);
});

it('can validate a bool', function () {
it('can validate a bool', function (bool $requireRuleForBooleans) {
$dataClass = new class () extends Data {
public bool $property;
};

config()->set('data.require_rule_for_booleans', $requireRuleForBooleans);

$rules = [];

if ($requireRuleForBooleans) {
$rules[] = 'required';
}

$rules[] = 'boolean';

DataValidationAsserter::for($dataClass)
->assertOk(['property' => true])
->assertRules([
'property' => ['boolean'],
'property' => $rules,
]);
});
})->with([true, false]);

it('can validate a nullable type', function () {
$dataClass = new class () extends Data {
Expand Down