Debian Codegraph @

includes/libs/ParamValidator/TypeDef/FloatDef.php

raw symbols SCIP
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 /** @inheritDoc */
32 protected $valueType = 'double';
33
34 public function validate( $name, $value, array $settings, array $options ) {
35 if ( is_float( $value ) ) {
36 $ret = $value;
37 } elseif ( is_int( $value ) ) {
38 $ret = (float)$value;
39 } elseif ( $options[ self::OPT_ENFORCE_JSON_TYPES ] ?? false ) {
40 $this->fatal(
41 $this->failureMessage( 'badfloat-type' )
42 ->params( gettype( $value ) ),
43 $name, $value, $settings, $options
44 );
45 } else {
46 if ( !preg_match( '/^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?$/D', $value ) ) {
47 // Use a regex to avoid any potential oddness PHP's default conversion might allow.
48 $this->fatal( 'badfloat', $name, $value, $settings, $options );
49 }
50
51 $ret = (float)$value;
52 }
53
54 if ( !is_finite( $ret ) ) {
55 $this->fatal( 'badfloat-notfinite', $name, $value, $settings, $options );
56 }
57
58 return $this->checkRange( $ret, $name, $value, $settings, $options );
59 }
60
61 public function stringifyValue( $name, $value, array $settings, array $options ) {
62 // Ensure sufficient precision for round-tripping
63 $digits = PHP_FLOAT_DIG;
64 return sprintf( "%.{$digits}g", $value );
65 }
66
67 public function getHelpInfo( $name, array $settings, array $options ) {
68 $info = parent::getHelpInfo( $name, $settings, $options );
69
70 $info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-float' )
71 ->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 );
72
73 return $info;
74 }
75
76 }