yiisoft / validator

Yii validator library
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
110 stars 36 forks source link

Callable rule attribute interface #466

Open vjik opened 1 year ago

vjik commented 1 year ago

Callable rule class may look like this:

final class MyRule {
    public function __invoke(mixed $value, object $rule, ValidationContext $context): Result {
        // ...
    }
}

For simple custom rules is good solution, but there is one problem. It is not possible usage as attribute.

We can add attribute Attribute:

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class MyRule {
    // ...

It's not enough, because validator parse attributes that implement RuleInterface only.

Suggest add new interface CallableRuleAttributeInterface and parse implementing its attributes in addition to RuleInterface.

xepozz commented 1 year ago

What the reason to have two the same interfaces but with different methods' names?

RuleInterface: validate($value, $rule, $context): Result

CallableRuleInterface: __invoke($value, $rule, $context): Result

vjik commented 1 year ago

CallableRuleInterface is not rule, it's callable only.

xepozz commented 1 year ago

What do you mean by it's callable only?

vjik commented 1 year ago

What do you mean by it's callable only?

It's not rule. Object does not implement RuleInterface.