trait-wc-item-totals.php
92 lines
| 1 | <?php |
| 2 | /** |
| 3 | * This ongoing trait will have shared calculation logic between WC_Abstract_Order and WC_Cart_Totals classes. |
| 4 | * |
| 5 | * @package WooCommerce\Traits |
| 6 | * @version 3.9.0 |
| 7 | */ |
| 8 | |
| 9 | use Automattic\WooCommerce\Utilities\NumberUtil; |
| 10 | |
| 11 | if ( ! defined( 'ABSPATH' ) ) { |
| 12 | exit; |
| 13 | } |
| 14 | |
| 15 | /** |
| 16 | * Trait WC_Item_Totals. |
| 17 | * |
| 18 | * Right now this do not have much, but plan is to eventually move all shared calculation logic between Orders and Cart in this file. |
| 19 | * |
| 20 | * @since 3.9.0 |
| 21 | */ |
| 22 | trait WC_Item_Totals { |
| 23 | |
| 24 | /** |
| 25 | * Line items to calculate. Define in child class. |
| 26 | * |
| 27 | * @since 3.9.0 |
| 28 | * @param string $field Field name to calculate upon. |
| 29 | * |
| 30 | * @return array having `total`|`subtotal` property. |
| 31 | */ |
| 32 | abstract protected function get_values_for_total( $field ); |
| 33 | |
| 34 | /** |
| 35 | * Return rounded total based on settings. Will be used by Cart and Orders. |
| 36 | * |
| 37 | * @since 3.9.0 |
| 38 | * |
| 39 | * @param array $values Values to round. Should be with precision. |
| 40 | * |
| 41 | * @return float|int Appropriately rounded value. |
| 42 | */ |
| 43 | public static function get_rounded_items_total( $values ) { |
| 44 | return array_sum( |
| 45 | array_map( |
| 46 | array( self::class, 'round_item_subtotal' ), |
| 47 | $values |
| 48 | ) |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Apply rounding to item subtotal before summing. |
| 54 | * |
| 55 | * @since 3.9.0 |
| 56 | * @param float $value Item subtotal value. |
| 57 | * @return float |
| 58 | */ |
| 59 | public static function round_item_subtotal( $value ) { |
| 60 | if ( ! self::round_at_subtotal() ) { |
| 61 | $value = NumberUtil::round( $value ); |
| 62 | } |
| 63 | return $value; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Should always round at subtotal? |
| 68 | * |
| 69 | * @since 3.9.0 |
| 70 | * @return bool |
| 71 | */ |
| 72 | protected static function round_at_subtotal() { |
| 73 | return 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' ); |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Apply rounding to an array of taxes before summing. Rounds to store DP setting, ignoring precision. |
| 78 | * |
| 79 | * @since 3.2.6 |
| 80 | * @param float $value Tax value. |
| 81 | * @param bool $in_cents Whether precision of value is in cents. |
| 82 | * @return float |
| 83 | */ |
| 84 | protected static function round_line_tax( $value, $in_cents = true ) { |
| 85 | if ( ! self::round_at_subtotal() ) { |
| 86 | $value = wc_round_tax_total( $value, $in_cents ? 0 : null ); |
| 87 | } |
| 88 | return $value; |
| 89 | } |
| 90 | |
| 91 | } |
| 92 |