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
35 public function validate( $name, $value, array $settings, array $options ) {
36 if ( is_float( $value ) ) {
37 $ret = $value;
38 } elseif ( is_int( $value ) ) {
39 $ret = (float)$value;
40 } elseif ( $options[ self::OPT_ENFORCE_JSON_TYPES ] ?? false ) {
41 $this->fatal(
42 $this->failureMessage( 'badfloat-type' )
43 ->params( gettype( $value ) ),
44 $name, $value, $settings, $options
45 );
46 } else {
47 if ( !preg_match( '/^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?$/D', $value ) ) {
48 // Use a regex to avoid any potential oddness PHP's default conversion might allow.
49 $this->fatal( 'badfloat', $name, $value, $settings, $options );
50 }
51
52 $ret = (float)$value;
53 }
54
55 if ( !is_finite( $ret ) ) {
56 $this->fatal( 'badfloat-notfinite', $name, $value, $settings, $options );
57 }
58
59 return $this->checkRange( $ret, $name, $value, $settings, $options );
60 }
61
63 public function stringifyValue( $name, $value, array $settings, array $options ) {
64 // Ensure sufficient precision for round-tripping
65 $digits = PHP_FLOAT_DIG;
66 return sprintf( "%.{$digits}g", $value );
67 }
68
70 public function getHelpInfo( $name, array $settings, array $options ) {
71 $info = parent::getHelpInfo( $name, $settings, $options );
72
73 $info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-float' )
74 ->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 );
75
76 return $info;
77 }
78
79}
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:70
validate( $name, $value, array $settings, array $options)
Validate the value.When ParamValidator is processing a multi-valued parameter, this will be called on...
Definition FloatDef.php:35
stringifyValue( $name, $value, array $settings, array $options)
Convert a value to a string representation.This is intended as the inverse of getValue() and validate...
Definition FloatDef.php:63
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