Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
FloatDef | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
6 | |
100.00% |
1 / 1 |
validate | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
stringifyValue | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
getHelpInfo | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 |
1 | <?php |
2 | |
3 | namespace Wikimedia\ParamValidator\TypeDef; |
4 | |
5 | use Wikimedia\Message\MessageValue; |
6 | use Wikimedia\ParamValidator\ParamValidator; |
7 | |
8 | /** |
9 | * Type definition for a floating-point type |
10 | * |
11 | * A valid representation consists of: |
12 | * - an optional sign (`+` or `-`) |
13 | * - a decimal number, using `.` as the decimal separator and no grouping |
14 | * - an optional E-notation suffix: the letter 'e' or 'E', an optional |
15 | * sign, and an integer |
16 | * |
17 | * Thus, for example, "12", "-.4", "6.022e23", or "+1.7e-10". |
18 | * |
19 | * The result from validate() is a PHP float. |
20 | * |
21 | * Failure codes: |
22 | * - 'badfloat': The value was invalid. No data. |
23 | * - 'badfloat-notfinite': The value was in a valid format, but conversion resulted in |
24 | * infinity or NAN. |
25 | * |
26 | * @since 1.34 |
27 | * @unstable |
28 | */ |
29 | class FloatDef extends NumericDef { |
30 | |
31 | protected $valueType = 'double'; |
32 | |
33 | public function validate( $name, $value, array $settings, array $options ) { |
34 | // Use a regex so as to avoid any potential oddness PHP's default conversion might allow. |
35 | if ( !preg_match( '/^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?$/D', $value ) ) { |
36 | $this->failure( 'badfloat', $name, $value, $settings, $options ); |
37 | } |
38 | |
39 | $ret = (float)$value; |
40 | if ( !is_finite( $ret ) ) { |
41 | $this->failure( 'badfloat-notfinite', $name, $value, $settings, $options ); |
42 | } |
43 | |
44 | return $this->checkRange( $ret, $name, $value, $settings, $options ); |
45 | } |
46 | |
47 | public function stringifyValue( $name, $value, array $settings, array $options ) { |
48 | // Ensure sufficient precision for round-tripping |
49 | $digits = PHP_FLOAT_DIG; |
50 | return sprintf( "%.{$digits}g", $value ); |
51 | } |
52 | |
53 | public function getHelpInfo( $name, array $settings, array $options ) { |
54 | $info = parent::getHelpInfo( $name, $settings, $options ); |
55 | |
56 | $info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-float' ) |
57 | ->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 ); |
58 | |
59 | return $info; |
60 | } |
61 | |
62 | } |