Debian Codegraph @

includes/libs/ParamValidator/TypeDef/IntegerDef.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\ParamValidator\TypeDef;
4
5 use Wikimedia\Message\MessageValue;
6 use Wikimedia\ParamValidator\ParamValidator;
7
8 /**
9 * Type definition for integer types
10 *
11 * A valid representation consists of an optional sign (`+` or `-`) followed by
12 * one or more decimal digits.
13 *
14 * The result from validate() is a PHP integer.
15 *
16 * * Failure codes:
17 * - 'badinteger': The value was invalid or could not be represented as a PHP
18 * integer. No data.
19 *
20 * @since 1.34
21 * @unstable
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 // Since JSON does not distinguish between integers and floats,
30 // floats without a fractional parts can be treated as integers.
31 // This is in line with the definition of the "integer" type in
32 // JSON Schema, see https://json-schema.org/understanding-json-schema/reference/numeric.
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 // Value is string and may exceed native int bounds.
52 // Ignore cast warnings, we will check if that happens later.
53 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
54 $ret = @intval( $value, 10 );
55 }
56 }
57
58 // intval() returns min/max on overflow, so check that
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 }