diff --git a/src/Rules/Boolean.php b/src/Rules/Boolean.php index c6dcd0c..b4dba06 100644 --- a/src/Rules/Boolean.php +++ b/src/Rules/Boolean.php @@ -7,6 +7,8 @@ use StellarWP\Validation\Contracts\ValidatesOnFrontEnd; use StellarWP\Validation\Contracts\ValidationRule; +use const FILTER_NULL_ON_FAILURE; + class Boolean implements ValidationRule, ValidatesOnFrontEnd, Sanitizer { /** @@ -32,12 +34,13 @@ public static function fromString(string $options = null): ValidationRule /** * {@inheritDoc} * + * @since 1.4.1 add is_bool check and FILTER_NULL_ON_FAILURE flag to prevent false positives * @since 1.4.0 */ public function __invoke($value, Closure $fail, string $key, array $values) { - if (!filter_var($value, FILTER_VALIDATE_BOOLEAN)) { - $fail(sprintf(__('%s must be an boolean', '%TEXTDOMAIN%'), '{field}')); + if (!is_bool(filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE))) { + $fail(sprintf(__('%s must be a boolean', '%TEXTDOMAIN%'), '{field}')); } } diff --git a/tests/unit/Rules/BooleanTest.php b/tests/unit/Rules/BooleanTest.php index 9ede234..89dd4b4 100644 --- a/tests/unit/Rules/BooleanTest.php +++ b/tests/unit/Rules/BooleanTest.php @@ -24,6 +24,7 @@ public function testRuleValidatesBooleans($value, $pass) } /** + * @since 1.4.1 updates tests to pass false-y values * @since 1.4.0 */ public function booleansProvider(): array @@ -36,15 +37,16 @@ public function booleansProvider(): array ['true', true], ['yes', true], ['on', true], + [false, true], + [0, true], + ['0', true], + ['false', true], + ['no', true], + ['off', true], // values that fail - [false, false], - [0, false], - ['0', false], - ['false', false], - ['no', false], - ['off', false], ['abc', false], + ['123', false], ]; }