square / laravel-hyrule

Object-oriented, composable, fluent API for writing validations in Laravel
Apache License 2.0
340 stars 10 forks source link

Improve rule normalization #12

Open bezhermoso opened 2 years ago

bezhermoso commented 2 years ago

Take AbstractNode#requiredIf:

In order to properly validate an optionally required field based on another boolean field, you'd need to do something like this:

$builder = Hyrule::create()
    ->boolean('needs_verification')
       ->end()
    ->file('proof')
       ->requiredIf('needs_verification', '1')
       ->end()
    ->end();

But that doesn't work correctly. This does:

$builder = Hyrule::create()
    ->boolean('needs_verification')
       ->end()
    ->file('proof')
       ->requiredIf('needs_verification', 'true') // <- Must use "true"
       ->end()
    ->end();

But ideally, it should just allow using a true boolean value:

$builder = Hyrule::create()
    ->boolean('needs_verification')
       ->end()
    ->file('proof')
       ->requiredIf('needs_verification', true) // <- Makes the most sense.
       ->end()
    ->end();

This PR loosens up the type requirements for requiredIf. It also brings proper normalization of true|false => "true"|"false" etc to other places e.g.

    ->anotherRule(false, null)
    // Before: another_rule:0,
    // Now: another_rule:false,NULL