| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Vendors\StellarWP\Validation\Rules; |
| 4 |
|
| 5 |
use Closure; |
| 6 |
use Give\Vendors\StellarWP\Validation\Contracts\Sanitizer; |
| 7 |
use Give\Vendors\StellarWP\Validation\Contracts\ValidatesOnFrontEnd; |
| 8 |
use Give\Vendors\StellarWP\Validation\Contracts\ValidationRule; |
| 9 |
|
| 10 |
use const FILTER_NULL_ON_FAILURE; |
| 11 |
|
| 12 |
class Boolean implements ValidationRule, ValidatesOnFrontEnd, Sanitizer |
| 13 |
{ |
| 14 |
/** |
| 15 |
* {@inheritDoc} |
| 16 |
* |
| 17 |
* @since 1.4.0 |
| 18 |
*/ |
| 19 |
public static function id(): string |
| 20 |
{ |
| 21 |
return 'boolean'; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* {@inheritDoc} |
| 26 |
* |
| 27 |
* @since 1.4.0 |
| 28 |
*/ |
| 29 |
public static function fromString(?string $options = null): ValidationRule |
| 30 |
{ |
| 31 |
return new self(); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* {@inheritDoc} |
| 36 |
* |
| 37 |
* @since 1.4.1 add is_bool check and FILTER_NULL_ON_FAILURE flag to prevent false positives |
| 38 |
* @since 1.4.0 |
| 39 |
*/ |
| 40 |
public function __invoke($value, Closure $fail, string $key, array $values) |
| 41 |
{ |
| 42 |
if (!is_bool(filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE))) { |
| 43 |
$fail(sprintf(__('%s must be a boolean', 'give'), '{field}')); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* {@inheritDoc} |
| 49 |
* |
| 50 |
* @since 1.4.0 |
| 51 |
*/ |
| 52 |
public function serializeOption() |
| 53 |
{ |
| 54 |
return null; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* {@inheritDoc} |
| 59 |
* |
| 60 |
* @since 1.4.0 |
| 61 |
*/ |
| 62 |
public function sanitize($value) |
| 63 |
{ |
| 64 |
return filter_var($value, FILTER_VALIDATE_BOOLEAN); |
| 65 |
} |
| 66 |
} |
| 67 |
|