forked from apoloz/alfa-bank-sdk
2.1 KiB
2.1 KiB
title, weight
| title | weight |
|---|---|
| Auto rule inferring | 2 |
The package will automatically infer validation rules from the data object. For example, for the following data class:
class ArtistData extends Data{
public function __construct(
public string $name,
public int $age,
public ?string $genre,
) {
}
}
The package will generate the following validation rules:
[
'name' => ['required', 'string'],
'age' => ['required', 'integer'],
'genre' => ['nullable', 'string'],
]
All these rules are inferred by RuleInferrers, special classes that will look at the types of properties and will add rules based upon that.
Rule inferrers are configured in the data.php config file:
/*
* Rule inferrers can be configured here. They will automatically add
* validation rules to properties of a data object based upon
* the type of the property.
*/
'rule_inferrers' => [
Spatie\LaravelData\RuleInferrers\SometimesRuleInferrer::class,
Spatie\LaravelData\RuleInferrers\NullableRuleInferrer::class,
Spatie\LaravelData\RuleInferrers\RequiredRuleInferrer::class,
Spatie\LaravelData\RuleInferrers\BuiltInTypesRuleInferrer::class,
Spatie\LaravelData\RuleInferrers\AttributesRuleInferrer::class,
],
By default, five rule inferrers are enabled:
- SometimesRuleInferrer will add a
sometimesrule when the property is optional - NullableRuleInferrer will add a
nullablerule when the property is nullable - RequiredRuleInferrer will add a
requiredrule when the property is not nullable - BuiltInTypesRuleInferrer will add a rules which are based upon the built-in php types:
- An
intorfloattype will add thenumericrule - A
booltype will add thebooleanrule - A
stringtype will add thestringrule - A
arraytype will add thearrayrule
- An
- AttributesRuleInferrer will make sure that rule attributes we described above will also add their rules
It is possible to write your rule inferrers. You can find more information here.