Nenhuma Descrição

trait-wc-item-totals.php 2.1KB

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