ArrayRule.php
6 days ago
BooleanRule.php
6 days ago
ConditionalRule.php
6 days ago
DateRule.php
6 days ago
ExistsRule.php
6 days ago
FileRule.php
6 days ago
InRule.php
6 days ago
NotInRule.php
6 days ago
NullableRule.php
6 days ago
NumericRule.php
6 days ago
ObjectRule.php
6 days ago
ProhibitedIfRule.php
6 days ago
ProhibitedRule.php
6 days ago
ProhibitedUnlessRule.php
6 days ago
RequiredIfRule.php
6 days ago
RequiredRule.php
6 days ago
RequiredUnlessRule.php
6 days ago
SameAsRule.php
6 days ago
SometimesRule.php
6 days ago
StringRule.php
6 days ago
UniqueRule.php
6 days ago
BooleanRule.php
91 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Boolean rule class. |
| 5 | * |
| 6 | * @package Framework |
| 7 | * @subpackage Validation |
| 8 | * @since 1.0.0 |
| 9 | */ |
| 10 | namespace Kirki\Framework\Validation\Rules; |
| 11 | |
| 12 | use Kirki\Framework\Validation\ValidationRule; |
| 13 | \defined('ABSPATH') || exit; |
| 14 | /** |
| 15 | * Validates that the given value is a boolean. |
| 16 | * |
| 17 | * Accepts true/false, 0/1, '0'/'1', 'true'/'false' by default. |
| 18 | * When the strict constraint is applied, only real booleans pass. |
| 19 | */ |
| 20 | class BooleanRule extends ValidationRule |
| 21 | { |
| 22 | /** |
| 23 | * The rule name. |
| 24 | * |
| 25 | * @var string |
| 26 | * |
| 27 | * @since 1.0.0 |
| 28 | */ |
| 29 | protected string $rule = 'boolean'; |
| 30 | /** |
| 31 | * The supported constraints. |
| 32 | * |
| 33 | * @var array |
| 34 | * |
| 35 | * @since 1.0.0 |
| 36 | */ |
| 37 | protected array $constraints = ['strict']; |
| 38 | /** |
| 39 | * The accepted boolean representations. |
| 40 | * |
| 41 | * @var array |
| 42 | * |
| 43 | * @since 1.0.0 |
| 44 | */ |
| 45 | protected array $accepted_values = [\true, \false, 0, 1, '0', '1', 'true', 'false']; |
| 46 | /** |
| 47 | * Create a new boolean rule instance. |
| 48 | * |
| 49 | * @param mixed $args The rule arguments. |
| 50 | * |
| 51 | * @return void |
| 52 | * |
| 53 | * @since 1.0.0 |
| 54 | */ |
| 55 | public function __construct($args = null) |
| 56 | { |
| 57 | parent::__construct($args); |
| 58 | if ($args === 'strict') { |
| 59 | $this->set('strict', \true); |
| 60 | } |
| 61 | } |
| 62 | /** |
| 63 | * Validate the rule. |
| 64 | * |
| 65 | * @return bool |
| 66 | * |
| 67 | * @since 1.0.0 |
| 68 | */ |
| 69 | public function validate() : bool |
| 70 | { |
| 71 | if ($this->get('strict') === \true) { |
| 72 | return \is_bool($this->value) ? \true : $this->fails($this->default_messages['default']); |
| 73 | } |
| 74 | if (!\in_array($this->value, $this->accepted_values, \true)) { |
| 75 | return $this->fails($this->default_messages['default']); |
| 76 | } |
| 77 | return \true; |
| 78 | } |
| 79 | /** |
| 80 | * Get the error messages. |
| 81 | * |
| 82 | * @return array |
| 83 | * |
| 84 | * @since 1.0.0 |
| 85 | */ |
| 86 | public function messages() |
| 87 | { |
| 88 | return $this->process_messages($this->messages); |
| 89 | } |
| 90 | } |
| 91 |