MediaWiki  1.34.0
FloatDef.php
Go to the documentation of this file.
1 <?php
2 
4 
7 
29 class FloatDef extends TypeDef {
30 
31  public function validate( $name, $value, array $settings, array $options ) {
32  // Use a regex so as to avoid any potential oddness PHP's default conversion might allow.
33  if ( !preg_match( '/^[+-]?(?:\d*\.)?\d+(?:[eE][+-]?\d+)?$/D', $value ) ) {
34  throw new ValidationException( $name, $value, $settings, 'badfloat', [] );
35  }
36 
37  $ret = (float)$value;
38  if ( !is_finite( $ret ) ) {
39  throw new ValidationException( $name, $value, $settings, 'notfinite', [] );
40  }
41 
42  return $ret;
43  }
44 
54  private function fixLocaleWeirdness( $value ) {
55  $localeData = localeconv();
56  if ( $localeData['decimal_point'] !== '.' ) {
57  $value = strtr( $value, [
58  $localeData['decimal_point'] => '.',
59  // PHP's number formatting currently uses only the first byte from 'decimal_point'.
60  // See upstream bug https://bugs.php.net/bug.php?id=78113
61  $localeData['decimal_point'][0] => '.',
62  ] );
63  }
64  return $value;
65  }
66 
67  public function stringifyValue( $name, $value, array $settings, array $options ) {
68  // Ensure sufficient precision for round-tripping. PHP_FLOAT_DIG was added in PHP 7.2.
69  $digits = defined( 'PHP_FLOAT_DIG' ) ? PHP_FLOAT_DIG : 15;
70  return $this->fixLocaleWeirdness( sprintf( "%.{$digits}g", $value ) );
71  }
72 
73 }
Wikimedia\ParamValidator\ValidationException
Error reporting for ParamValidator.
Definition: ValidationException.php:15
Wikimedia\ParamValidator\TypeDef\FloatDef\fixLocaleWeirdness
fixLocaleWeirdness( $value)
Attempt to fix locale weirdness.
Definition: FloatDef.php:54
Wikimedia\ParamValidator\TypeDef
Base definition for ParamValidator types.
Definition: TypeDef.php:15
Wikimedia\ParamValidator\TypeDef\FloatDef
Type definition for a floating-point type.
Definition: FloatDef.php:29
Wikimedia\ParamValidator\TypeDef\FloatDef\stringifyValue
stringifyValue( $name, $value, array $settings, array $options)
Convert a value to a string representation.
Definition: FloatDef.php:67
Wikimedia\ParamValidator\TypeDef\FloatDef\validate
validate( $name, $value, array $settings, array $options)
Validate the value.
Definition: FloatDef.php:31
Wikimedia\ParamValidator\TypeDef
Definition: BooleanDef.php:3