Merge "Chinese Conversion Table Update 2019-2"
[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 */
21 class BooleanDef extends TypeDef {
22
23 public static $TRUEVALS = [ 'true', 't', 'yes', 'y', 'on', '1' ];
24 public static $FALSEVALS = [ 'false', 'f', 'no', 'n', 'off', '0' ];
25
26 public function validate( $name, $value, array $settings, array $options ) {
27 $value = strtolower( $value );
28 if ( in_array( $value, self::$TRUEVALS, true ) ) {
29 return true;
30 }
31 if ( $value === '' || in_array( $value, self::$FALSEVALS, true ) ) {
32 return false;
33 }
34
35 throw new ValidationException( $name, $value, $settings, 'badbool', [
36 'truevals' => self::$TRUEVALS,
37 'falsevals' => array_merge( self::$FALSEVALS, [ 'the empty string' ] ),
38 ] );
39 }
40
41 public function stringifyValue( $name, $value, array $settings, array $options ) {
42 return $value ? self::$TRUEVALS[0] : self::$FALSEVALS[0];
43 }
44
45 }