| 1 |
<?php |
| 2 |
/** |
| 3 |
* A class of utilities for dealing with numbers. |
| 4 |
*/ |
| 5 |
|
| 6 |
namespace StoreEngine\Utils; |
| 7 |
|
| 8 |
if ( ! defined( 'ABSPATH' ) ) { |
| 9 |
exit; |
| 10 |
} |
| 11 |
|
| 12 |
/** |
| 13 |
* A class of utilities for dealing with numbers. |
| 14 |
*/ |
| 15 |
final class NumberUtil { |
| 16 |
/** |
| 17 |
* Round a number using the built-in `round` function, but unless the value to round is numeric |
| 18 |
* (a number or a string that can be parsed as a number), apply 'floatval' first to it |
| 19 |
* (so it will convert it to 0 in most cases). |
| 20 |
* |
| 21 |
* This is needed because in PHP 7 applying `round` to a non-numeric value returns 0, |
| 22 |
* but in PHP 8 it throws an error. Specifically, in StoreEngine we have a few places where |
| 23 |
* round('') is often executed. |
| 24 |
* |
| 25 |
* @param mixed $val The value to round. |
| 26 |
* @param int $precision The optional number of decimal digits to round to. |
| 27 |
* @param int $mode A constant to specify the mode in which rounding occurs. |
| 28 |
* |
| 29 |
* @return float The value rounded to the given precision as a float, or the supplied default value. |
| 30 |
*/ |
| 31 |
public static function round( $val, int $precision = 0, int $mode = PHP_ROUND_HALF_UP ) : float { |
| 32 |
if ( ! is_numeric( $val ) ) { |
| 33 |
$val = floatval( $val ); |
| 34 |
} |
| 35 |
|
| 36 |
return round( $val, $precision, $mode ); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Get the sum of an array of values using the built-in array_sum function, but sanitize the array values |
| 41 |
* first to ensure they are all floats. |
| 42 |
* |
| 43 |
* This is needed because in PHP 8.3 non-numeric values that cannot be cast as an int or a float will |
| 44 |
* cause an E_WARNING to be emitted. Prior to PHP 8.3 these values were just ignored. |
| 45 |
* |
| 46 |
* Note that, unlike the built-in array_sum, this one will always return a float, never an int. |
| 47 |
* |
| 48 |
* @param array $arr The array of values to sum. |
| 49 |
* |
| 50 |
* @return float |
| 51 |
*/ |
| 52 |
public static function array_sum( array $arr ): float { |
| 53 |
$sanitized_array = array_map( 'floatval', $arr ); |
| 54 |
|
| 55 |
return array_sum( $sanitized_array ); |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Array sum with a callback applied to the array before doing the sum. |
| 60 |
* |
| 61 |
* @see self::array_sum() |
| 62 |
* |
| 63 |
* @param array $arr The array of values to sum. |
| 64 |
* @param ?callable $callback The callback function. |
| 65 |
* |
| 66 |
* @return float |
| 67 |
*/ |
| 68 |
public static function uarray_sum( array $arr, ?callable $callback = null ): float { |
| 69 |
if ( ! $callback ) { |
| 70 |
return self::array_sum( $arr ); |
| 71 |
} |
| 72 |
|
| 73 |
return self::array_sum( array_map( $callback, $arr) ); |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
// End of file number-util.php. |
| 78 |
|