CurrencyFormatter.php
2 years ago
DefaultFormatter.php
2 years ago
FormatterInterface.php
2 years ago
HtmlFormatter.php
2 years ago
MoneyFormatter.php
1 year ago
MoneyFormatter.php
54 lines
| 1 | <?php |
| 2 | namespace Automattic\WooCommerce\StoreApi\Formatters; |
| 3 | |
| 4 | /** |
| 5 | * Money Formatter. |
| 6 | * |
| 7 | * Formats monetary values using store settings. |
| 8 | */ |
| 9 | class MoneyFormatter implements FormatterInterface { |
| 10 | /** |
| 11 | * Format a given price value and return the result as a string without decimals. |
| 12 | * |
| 13 | * @param int|float|string $value Value to format. Int is allowed, as it may also represent a valid price. |
| 14 | * @param array $options Options that influence the formatting. |
| 15 | * @return string |
| 16 | */ |
| 17 | public function format( $value, array $options = [] ) { |
| 18 | |
| 19 | if ( ! is_int( $value ) && ! is_string( $value ) && ! is_float( $value ) ) { |
| 20 | wc_doing_it_wrong( |
| 21 | __FUNCTION__, |
| 22 | 'Function expects a $value arg of type INT, STRING or FLOAT.', |
| 23 | '9.2' |
| 24 | ); |
| 25 | |
| 26 | return ''; |
| 27 | } |
| 28 | |
| 29 | $options = wp_parse_args( |
| 30 | $options, |
| 31 | [ |
| 32 | 'decimals' => wc_get_price_decimals(), |
| 33 | 'rounding_mode' => PHP_ROUND_HALF_UP, |
| 34 | ] |
| 35 | ); |
| 36 | |
| 37 | // Ensure rounding mode is valid. |
| 38 | $rounding_modes = [ PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD ]; |
| 39 | $options['rounding_mode'] = absint( $options['rounding_mode'] ); |
| 40 | if ( ! in_array( $options['rounding_mode'], $rounding_modes, true ) ) { |
| 41 | $options['rounding_mode'] = PHP_ROUND_HALF_UP; |
| 42 | } |
| 43 | |
| 44 | $value = floatval( $value ); |
| 45 | |
| 46 | // Remove the price decimal points for rounding purposes. |
| 47 | $value = $value * pow( 10, absint( $options['decimals'] ) ); |
| 48 | $value = round( $value, 0, $options['rounding_mode'] ); |
| 49 | |
| 50 | // This ensures returning the value as a string without decimal points ready for price parsing. |
| 51 | return wc_format_decimal( $value, 0, true ); |
| 52 | } |
| 53 | } |
| 54 |