ArrayUtil.php
1 year ago
CallbackUtil.php
5 months ago
DiscountsUtil.php
2 years ago
FeaturesUtil.php
5 months ago
I18nUtil.php
3 years ago
LoggingUtil.php
1 year ago
MetaDataUtil.php
2 months ago
NumberUtil.php
11 months ago
OrderUtil.php
7 months ago
PluginUtil.php
4 weeks ago
RestApiUtil.php
7 months ago
ShippingUtil.php
1 year ago
StringUtil.php
2 years ago
TimeUtil.php
2 years ago
NumberUtil.php
194 lines
| 1 | <?php //phpcs:ignore Generic.PHP.RequireStrictTypes.MissingDeclaration |
| 2 | // many places seem to be calling round with a string, and that causes PHP > 8.1 to throw a TypeError. |
| 3 | // It's not respecting the 'mixed' type hint in the docblock, and type unions aren't supported until PHP > 8.0. |
| 4 | // so I'm not sure how to handle this since adding the type union will cause errors below PHP < 8.0. |
| 5 | /** |
| 6 | * A class of utilities for dealing with numbers. |
| 7 | */ |
| 8 | |
| 9 | |
| 10 | namespace Automattic\WooCommerce\Utilities; |
| 11 | |
| 12 | /** |
| 13 | * A class of utilities for dealing with numbers. |
| 14 | */ |
| 15 | final class NumberUtil { |
| 16 | /** |
| 17 | * Converts numbers (floats, strings, integers) to numeric values to be safely used in PHP functions like floor() which expect int or float. |
| 18 | * |
| 19 | * @param mixed $value The value to convert. |
| 20 | * @param mixed $fallback The value to return if the conversion fails. |
| 21 | * @return int|float|mixed Returns the numeric value or the fallback value if conversion fails. |
| 22 | */ |
| 23 | public static function normalize( $value, $fallback = 0 ) { |
| 24 | // Trim string values to handle whitespace consistently across PHP versions. |
| 25 | if ( is_string( $value ) ) { |
| 26 | $value = trim( $value ); |
| 27 | } |
| 28 | |
| 29 | if ( is_numeric( $value ) ) { |
| 30 | $numeric_value = is_string( $value ) ? floatval( $value ) : $value; |
| 31 | |
| 32 | // Round to precision to avoid floating-point precision issues. |
| 33 | return is_int( $numeric_value ) ? $numeric_value : round( $numeric_value, WC_ROUNDING_PRECISION ); |
| 34 | } |
| 35 | |
| 36 | return $fallback; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Round a number using the built-in `round` function, but unless the value to round is numeric |
| 41 | * (a number or a string that can be parsed as a number), apply 'floatval' first to it |
| 42 | * (so it will convert it to 0 in most cases). |
| 43 | * |
| 44 | * This is needed because in PHP 7 applying `round` to a non-numeric value returns 0, |
| 45 | * but in PHP 8 it throws an error. Specifically, in WooCommerce we have a few places where |
| 46 | * round('') is often executed. |
| 47 | * |
| 48 | * @param mixed $val The value to round. |
| 49 | * @param int $precision The optional number of decimal digits to round to. |
| 50 | * @param int $mode A constant to specify the mode in which rounding occurs. |
| 51 | * |
| 52 | * @return float The value rounded to the given precision as a float. |
| 53 | */ |
| 54 | public static function round( $val, int $precision = 0, int $mode = PHP_ROUND_HALF_UP ): float { |
| 55 | return round( self::normalize( $val ), $precision, $mode ); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Floor a number using the built-in `floor` function. |
| 60 | * |
| 61 | * @param mixed $val The value to floor. |
| 62 | * @return float |
| 63 | */ |
| 64 | public static function floor( $val ): float { |
| 65 | return floor( self::normalize( $val ) ); |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Ceil a number using the built-in `ceil` function. |
| 70 | * |
| 71 | * @param mixed $val The value to ceil. |
| 72 | * @return float |
| 73 | */ |
| 74 | public static function ceil( $val ): float { |
| 75 | return ceil( self::normalize( $val ) ); |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Get the sum of an array of values using the built-in array_sum function, but sanitize the array values |
| 80 | * first to ensure they are all floats. |
| 81 | * |
| 82 | * This is needed because in PHP 8.3 non-numeric values that cannot be cast as an int or a float will |
| 83 | * cause an E_WARNING to be emitted. Prior to PHP 8.3 these values were just ignored. |
| 84 | * |
| 85 | * Note that, unlike the built-in array_sum, this one will always return a float, never an int. |
| 86 | * |
| 87 | * @param array $arr The array of values to sum. |
| 88 | * |
| 89 | * @return float |
| 90 | */ |
| 91 | public static function array_sum( array $arr ): float { |
| 92 | $sanitized_array = array_map( 'floatval', $arr ); |
| 93 | |
| 94 | return array_sum( $sanitized_array ); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Sanitize a cost value based on the current locale decimal and thousand separators. |
| 99 | * |
| 100 | * @param string $value The value to sanitize. |
| 101 | * @return string The sanitized value. |
| 102 | * @throws \InvalidArgumentException If the value is not a valid numeric value. |
| 103 | */ |
| 104 | public static function sanitize_cost_in_current_locale( $value ): string { |
| 105 | $value = is_null( $value ) ? '' : $value; |
| 106 | $value = wp_kses_post( trim( wp_unslash( $value ) ) ); |
| 107 | $currency_symbol_encoded = get_woocommerce_currency_symbol(); |
| 108 | $currency_symbol_variations = array( $currency_symbol_encoded, wp_kses_normalize_entities( $currency_symbol_encoded ), html_entity_decode( $currency_symbol_encoded, ENT_COMPAT ) ); |
| 109 | |
| 110 | $value = str_replace( $currency_symbol_variations, '', $value ); |
| 111 | |
| 112 | // Count the number of decimal points. |
| 113 | $decimal_point_count = substr_count( $value, '.' ); |
| 114 | |
| 115 | // If it's a standard decimal number (single decimal point and is_numeric), accept it directly. This could be in the case where the frontend has de-localised the value. |
| 116 | // We check for the decimal point count in addition to using is_numeric. |
| 117 | // This is because is_numeric is much looser and accepts non-base10 numbers as well as 'e' to demarcate exponents. |
| 118 | if ( 1 === $decimal_point_count && is_numeric( $value ) ) { |
| 119 | return $value; |
| 120 | } |
| 121 | |
| 122 | // Otherwise, attempt to delocalise according to localisation rules. |
| 123 | $allowed_characters_regex = sprintf( |
| 124 | '/^[0-9\%s\%s]*$/', |
| 125 | wc_get_price_thousand_separator(), |
| 126 | wc_get_price_decimal_separator() |
| 127 | ); |
| 128 | |
| 129 | if ( 1 !== preg_match( $allowed_characters_regex, $value ) ) { |
| 130 | throw new \InvalidArgumentException( |
| 131 | esc_html( |
| 132 | sprintf( |
| 133 | /* translators: %1$s: Invalid value that was input by the user, %2$s: thousand separator, %3$s: decimal separator */ |
| 134 | __( '%1$s is not a valid numeric value. Allowed characters are numbers, the thousand (%2$s), and decimal (%3$s) separators.', 'woocommerce' ), |
| 135 | $value, |
| 136 | wc_get_price_thousand_separator(), |
| 137 | wc_get_price_decimal_separator() |
| 138 | ) |
| 139 | ) |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | // Validate decimal and thousand separator positions. |
| 144 | $decimal_separator = wc_get_price_decimal_separator(); |
| 145 | $thousand_separator = wc_get_price_thousand_separator(); |
| 146 | |
| 147 | if ( |
| 148 | // Check that there is only 1 decimal separator. |
| 149 | substr_count( $value, $decimal_separator ) > 1 || |
| 150 | ( |
| 151 | // Check that decimal separator appears after thousand separator if both exist. |
| 152 | false !== strpos( $value, $thousand_separator ) && |
| 153 | false !== strpos( $value, $decimal_separator ) && |
| 154 | strpos( $value, $decimal_separator ) <= strpos( $value, $thousand_separator ) |
| 155 | ) |
| 156 | ) { |
| 157 | throw new \InvalidArgumentException( |
| 158 | esc_html( |
| 159 | sprintf( |
| 160 | /* translators: %s: Invalid value that was input by the user */ |
| 161 | __( '%s is not a valid numeric value: there should be one decimal separator and it has to be after the thousands separator.', 'woocommerce' ), |
| 162 | $value |
| 163 | ) |
| 164 | ) |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * For context, as of 2025. |
| 170 | * The full set of thousands separators is PERIOD, COMMA, SPACE, APOSTROPHE. |
| 171 | * And the full set of decimal separators is PERIOD, COMMA. |
| 172 | * There are no locales that use the same thousands and decimal separators. |
| 173 | */ |
| 174 | |
| 175 | $value = str_replace( wc_get_price_thousand_separator(), '', $value ); |
| 176 | $value = str_replace( wc_get_price_decimal_separator(), '.', $value ); |
| 177 | |
| 178 | if ( $value && ! is_numeric( $value ) ) { |
| 179 | /* translators: %s: Invalid value that was input by the user */ |
| 180 | throw new \InvalidArgumentException( |
| 181 | esc_html( |
| 182 | sprintf( |
| 183 | /* translators: %s: Invalid value that was input by the user */ |
| 184 | __( '%s is not a valid numeric value.', 'woocommerce' ), |
| 185 | $value |
| 186 | ) |
| 187 | ) |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | return $value; |
| 192 | } |
| 193 | } |
| 194 |