ParamValidator: Flag as unstable for 1.34
[lhc/web/wiklou.git] / includes / libs / ParamValidator / TypeDef / BooleanDef.php
1 <?php
2
3 namespace Wikimedia\ParamValidator\TypeDef;
4
5 use Wikimedia\ParamValidator\TypeDef;
6 use Wikimedia\ParamValidator\ValidationException;
7
8 /**
9 * Type definition for boolean types
10 *
11 * This type accepts certain defined strings to mean 'true' or 'false'.
12 * The result from validate() is a PHP boolean.
13 *
14 * ValidationException codes:
15 * - 'badbool': The value is not a recognized boolean. Data:
16 * - 'truevals': List of recognized values for "true".
17 * - 'falsevals': List of recognized values for "false".
18 *
19 * @since 1.34
20 * @unstable
21 */
22 class BooleanDef extends TypeDef {
23
24 public static $TRUEVALS = [ 'true', 't', 'yes', 'y', 'on', '1' ];
25 public static $FALSEVALS = [ 'false', 'f', 'no', 'n', 'off', '0' ];
26
27 public function validate( $name, $value, array $settings, array $options ) {
28 $value = strtolower( $value );
29 if ( in_array( $value, self::$TRUEVALS, true ) ) {
30 return true;
31 }
32 if ( $value === '' || in_array( $value, self::$FALSEVALS, true ) ) {
33 return false;
34 }
35
36 throw new ValidationException( $name, $value, $settings, 'badbool', [
37 'truevals' => self::$TRUEVALS,
38 'falsevals' => array_merge( self::$FALSEVALS, [ 'the empty string' ] ),
39 ] );
40 }
41
42 public function stringifyValue( $name, $value, array $settings, array $options ) {
43 return $value ? self::$TRUEVALS[0] : self::$FALSEVALS[0];
44 }
45
46 }