| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\ParamValidator\TypeDef; |
| 4 |
|
| 5 |
use Wikimedia\Message\MessageValue; |
| 6 |
use Wikimedia\ParamValidator\ParamValidator; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
class IntegerDef extends NumericDef { |
| 24 |
|
| 25 |
public function validate( $name, $value, array $settings, array $options ) { |
| 26 |
if ( is_int( $value ) ) { |
| 27 |
$ret = $value; |
| 28 |
} elseif ( is_float( $value ) ) { |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
$ret = intval( $value ); |
| 34 |
if ( $ret - $value !== 0.0 ) { |
| 35 |
$this->fatal( |
| 36 |
$this->failureMessage( 'badinteger-fraction' ) |
| 37 |
->params( gettype( $value ) ), |
| 38 |
$name, $value, $settings, $options |
| 39 |
); |
| 40 |
} |
| 41 |
} elseif ( $options[ self::OPT_ENFORCE_JSON_TYPES ] ?? false ) { |
| 42 |
$this->fatal( |
| 43 |
$this->failureMessage( 'badinteger-type' ) |
| 44 |
->params( gettype( $value ) ), |
| 45 |
$name, $value, $settings, $options |
| 46 |
); |
| 47 |
} else { |
| 48 |
if ( is_array( $value ) || !preg_match( '/^[+-]?\d+$/D', $value ) ) { |
| 49 |
$this->fatal( 'badinteger', $name, $value, $settings, $options ); |
| 50 |
} else { |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
$ret = @intval( $value, 10 ); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
if ( $ret === PHP_INT_MAX || $ret === PHP_INT_MIN ) { |
| 60 |
$tmp = ( $ret < 0 ? '-' : '' ) . ltrim( $value, '-0' ); |
| 61 |
if ( $tmp !== (string)$ret ) { |
| 62 |
$this->failure( 'badinteger', $name, $value, $settings, $options ); |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
return $this->checkRange( $ret, $name, $value, $settings, $options ); |
| 67 |
} |
| 68 |
|
| 69 |
public function getHelpInfo( $name, array $settings, array $options ) { |
| 70 |
$info = parent::getHelpInfo( $name, $settings, $options ); |
| 71 |
|
| 72 |
$info[ParamValidator::PARAM_TYPE] = MessageValue::new( 'paramvalidator-help-type-integer' ) |
| 73 |
->params( empty( $settings[ParamValidator::PARAM_ISMULTI] ) ? 1 : 2 ); |
| 74 |
|
| 75 |
return $info; |
| 76 |
} |
| 77 |
|
| 78 |
public function stringifyValue( $name, $value, array $settings, array $options ) { |
| 79 |
if ( !is_array( $value ) ) { |
| 80 |
return parent::stringifyValue( $name, $value, $settings, $options ); |
| 81 |
} |
| 82 |
|
| 83 |
return ParamValidator::implodeMultiValue( $value ); |
| 84 |
} |
| 85 |
|
| 86 |
} |