validator
validator copied to clipboard
Add `CallbackRule` rule
This is analogue of Callback but it returns a different rule that is already being applied.
Example of usage:
/**
* @var array<int, string>
*/
private readonly array $categories;
#[CallbackRule(method: categoryIdRule)]
public int|null $categoryId = null;
private function categoryIdRule(): RuleInterface
{
return new In(array_keys($this->categories));
}
How this example may be implemented with Callback rule?
How this example may be implemented with
Callbackrule?
Only with manual validation in categoryIdRule method
Is it bad?
Is it bad?
It's not convenient
Something like this?
/**
* @var array<int, string>
*/
private readonly array $categories;
#[Callback(method: categoryIdRule)]
public int|null $categoryId = null;
private function categoryIdRule(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
return $context->validate($value, new In(array_keys($this->categories)));
}
Something like this?
/**
- @var array<int, string> */ private readonly array $categories;
#[Callback(method: categoryIdRule)] public int|null $categoryId = null;
private function categoryIdRule(mixed $value, RuleInterface $rule, ValidationContext $context): Result { return $context->validate($value, new In(array_keys($this->categories))); }
Yes
I'm not sure this worth it. It only removes $context->validate($value part
While this new syntax removes some code, it is quite confusing since it adds a third way to do the same thing. One way is what @BoShurik suggested (a bit longer but is clear about what happens there), another is by implementing RulesProviderInterface (also clear, the only disadvantage is that declaration isn't at the same place as the property).
Personally, I'd avoid adding another way to do the same thing.
Callable for Callback:
private function categoryIdRule(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
return $context->validate($value, new In(array_keys($this->categories)));
}
Callable for CallbackRule:
private function categoryIdRule(): RuleInterface
{
return new In(array_keys($this->categories));
}
Seems, CallbackRule usage is more clearly. Also not need remember this: mixed $value, RuleInterface $rule, ValidationContext $context (no autocomplete for callable parameters).