MediaWiki master
FloatDef.php
Go to the documentation of this file.
1<?php
2
4
7
29class FloatDef extends NumericDef {
30
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}
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:67
validate( $name, $value, array $settings, array $options)
Validate the value.
Definition FloatDef.php:34
stringifyValue( $name, $value, array $settings, array $options)
Convert a value to a string representation.
Definition FloatDef.php:61
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