Debian Codegraph @

includes/libs/ParamValidator/TypeDef/BooleanDef.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\ParamValidator\TypeDef;
4
5 use Wikimedia\Message\MessageValue;
6 use Wikimedia\Message\ParamType;
7 use Wikimedia\Message\ScalarParam;
8 use Wikimedia\ParamValidator\ParamValidator;
9 use Wikimedia\ParamValidator\TypeDef;
10
11 /**
12 * Type definition for boolean types
13 *
14 * This type accepts certain defined strings to mean 'true' or 'false'.
15 * The result from validate() is a PHP boolean.
16 *
17 * Failure codes:
18 * - 'badbool': The value is not a recognized boolean. No data.
19 *
20 * @since 1.34
21 * @unstable
22 */
23 class BooleanDef extends TypeDef {
24
25 public const TRUEVALS = [ 'true', 't', 'yes', 'y', 'on', '1' ];
26 public const FALSEVALS = [ 'false', 'f', 'no', 'n', 'off', '0' ];
27
28 public function validate( $name, $value, array $settings, array $options ) {
29 if ( is_bool( $value ) ) {
30 return $value;
31 } elseif ( $options[ self::OPT_ENFORCE_JSON_TYPES ] ?? false ) {
32 $this->fatal(
33 $this->failureMessage( 'badbool-type' )
34 ->params( gettype( $value ) ),
35 $name, $value, $settings, $options
36 );
37 }
38
39 $value = strtolower( $value );
40 if ( in_array( $value, self::TRUEVALS, true ) ) {
41 return true;
42 }
43 if ( $value === '' || in_array( $value, self::FALSEVALS, true ) ) {
44 return false;
45 }
46
47 $this->fatal(
48 $this->failureMessage( 'badbool' )
49 ->textListParams( array_map( [ $this, 'quoteVal' ], self::TRUEVALS ) )
50 ->numParams( count( self::TRUEVALS ) )
51 ->textListParams( array_merge(
52 array_map( [ $this, 'quoteVal' ], self::FALSEVALS ),
53 [ MessageValue::new( 'paramvalidator-emptystring' ) ]
54 ) )
55 ->numParams( count( self::FALSEVALS ) + 1 ),
56 $name, $value, $settings, $options
57 );
58 }
59
60 private function quoteVal( $v ) {
61 return new ScalarParam( ParamType::TEXT, "\"$v\"" );
62 }
63
64 public function stringifyValue( $name, $value, array $settings, array $options ) {
65 return $value ? self::TRUEVALS[0] : self::FALSEVALS[0];
66 }
67
68 public function getHelpInfo( $name, array $settings, array $options ) {
69 $info = parent::getHelpInfo( $name, $settings, $options );
70
71 $info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-boolean' )
72 ->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 );
73
74 return $info;
75 }
76
77 }