TaxCalculator.php
75 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Class TaxCalculator |
| 4 | * |
| 5 | * @package WPDesk\FS\TableRate\Tax |
| 6 | */ |
| 7 | |
| 8 | namespace WPDesk\FS\TableRate\Tax; |
| 9 | |
| 10 | use FSVendor\WPDesk\FS\TableRate\Settings\MethodSettingsImplementation; |
| 11 | |
| 12 | /** |
| 13 | * Can calculate taxes for rates. |
| 14 | */ |
| 15 | class TaxCalculator { |
| 16 | |
| 17 | const TAXABLE = 'taxable'; |
| 18 | const COST = 'cost'; |
| 19 | |
| 20 | /** |
| 21 | * @var MethodSettingsImplementation |
| 22 | */ |
| 23 | private $method_settings; |
| 24 | |
| 25 | /** |
| 26 | * @var array |
| 27 | */ |
| 28 | private $tax_rates; |
| 29 | |
| 30 | /** |
| 31 | * TaxCalculator constructor. |
| 32 | * |
| 33 | * @param MethodSettingsImplementation $method_settings . |
| 34 | */ |
| 35 | public function __construct( MethodSettingsImplementation $method_settings, array $tax_rates ) { |
| 36 | $this->method_settings = $method_settings; |
| 37 | $this->tax_rates = $tax_rates; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * @param array $rate . |
| 42 | * @param bool $is_customer_vat_exempt . |
| 43 | */ |
| 44 | public function append_taxes_to_rate_if_enabled( array $rate, $is_customer_vat_exempt ) { |
| 45 | if ( wc_tax_enabled() && 'yes' === $this->method_settings->get_prices_include_tax() |
| 46 | && self::TAXABLE === $this->method_settings->get_tax_status() |
| 47 | && isset( $rate[ self::COST ] ) && 0.0 !== (float) $rate[ self::COST ] |
| 48 | ) { |
| 49 | return $this->append_taxes_to_rate( $rate, $is_customer_vat_exempt ); |
| 50 | } |
| 51 | |
| 52 | return $rate; |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * @param array $rate . |
| 57 | * @param bool $is_customer_vat_exempt . |
| 58 | * |
| 59 | * @return array |
| 60 | */ |
| 61 | private function append_taxes_to_rate( array $rate, bool $is_customer_vat_exempt ) { |
| 62 | $total_cost = $rate[ self::COST ]; |
| 63 | $taxes = \WC_Tax::calc_tax( $total_cost, $this->tax_rates, true ); |
| 64 | |
| 65 | $rate[ self::COST ] = $total_cost - array_sum( $taxes ); |
| 66 | |
| 67 | $rate['taxes'] = $is_customer_vat_exempt ? [] : \WC_Tax::calc_shipping_tax( $rate[ self::COST ], $this->tax_rates ); |
| 68 | |
| 69 | $rate['price_decimals'] = '4'; // Prevent the cost from being rounded before the tax is added. |
| 70 | |
| 71 | return $rate; |
| 72 | } |
| 73 | |
| 74 | } |
| 75 |