MediaWiki master
FloatDef.php
Go to the documentation of this file.
1<?php
2
4
7
29class FloatDef extends NumericDef {
30
31 protected $valueType = 'double';
32
33 public function validate( $name, $value, array $settings, array $options ) {
34 if ( is_float( $value ) ) {
35 $ret = $value;
36 } elseif ( is_int( $value ) ) {
37 $ret = (float)$value;
38 } elseif ( $options[ self::OPT_ENFORCE_JSON_TYPES ] ?? false ) {
39 $this->fatal(
40 $this->failureMessage( 'badfloat-type' )
41 ->params( gettype( $value ) ),
42 $name, $value, $settings, $options
43 );
44 } else {
45 if ( !preg_match( '/^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?$/D', $value ) ) {
46 // Use a regex to avoid any potential oddness PHP's default conversion might allow.
47 $this->fatal( 'badfloat', $name, $value, $settings, $options );
48 }
49
50 $ret = (float)$value;
51 }
52
53 if ( !is_finite( $ret ) ) {
54 $this->fatal( 'badfloat-notfinite', $name, $value, $settings, $options );
55 }
56
57 return $this->checkRange( $ret, $name, $value, $settings, $options );
58 }
59
60 public function stringifyValue( $name, $value, array $settings, array $options ) {
61 // Ensure sufficient precision for round-tripping
62 $digits = PHP_FLOAT_DIG;
63 return sprintf( "%.{$digits}g", $value );
64 }
65
66 public function getHelpInfo( $name, array $settings, array $options ) {
67 $info = parent::getHelpInfo( $name, $settings, $options );
68
69 $info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-float' )
70 ->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 );
71
72 return $info;
73 }
74
75}
Value object representing a message for i18n.
Service for formatting and validating API parameters.
const PARAM_ISMULTI
(bool) Indicate that the parameter is multi-valued.
const PARAM_TYPE
(string|array) Type of the parameter.
Type definition for a floating-point type.
Definition FloatDef.php:29
getHelpInfo( $name, array $settings, array $options)
Describe parameter settings in human-readable format.Keys in the returned array should generally corr...
Definition FloatDef.php:66
validate( $name, $value, array $settings, array $options)
Validate the value.
Definition FloatDef.php:33
stringifyValue( $name, $value, array $settings, array $options)
Convert a value to a string representation.
Definition FloatDef.php:60
Type definition base class for numeric types.
checkRange( $value, $name, $origValue, array $settings, array $options)
Check the range of a value.
fatal( $failure, $name, $value, array $settings, array $options)
Throw a ValidationException.
Definition TypeDef.php:99
failureMessage( $code, array $data=null, $suffix=null)
Create a DataMessageValue representing a failure.
Definition TypeDef.php:156