Created
May 3, 2018 14:59
-
-
Save mlewis-everley/051651771bd07a445857eb1e470cce30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Helper class designed to reduce the vat rates on order items when a | |
* BookableProduct is added to cart. | |
* | |
*/ | |
class VatReducer extends Object | |
{ | |
/** | |
* The rate of VAT that will be removed from the item | |
* | |
* @var float | |
*/ | |
protected $vat_rate; | |
/** | |
* Get the value of vat_rate | |
* | |
* @return float | |
*/ | |
public function getVatRate() | |
{ | |
return $this->vat_rate; | |
} | |
/** | |
* Set the value of vat_rate | |
* | |
* @param float $vat_rate The vat rate to set | |
* | |
* @return self | |
*/ | |
public function setVatRate(int $vat_rate) | |
{ | |
$this->vat_rate = $vat_rate; | |
return $this; | |
} | |
/** | |
* The price that will be having VAT removed | |
* | |
* @var float | |
*/ | |
protected $price; | |
/** | |
* Get the value of price | |
* | |
* @return float | |
*/ | |
public function getPrice() | |
{ | |
return $this->price; | |
} | |
/** | |
* Set the value of price | |
* | |
* @param float $price The price to set | |
* | |
* @return self | |
*/ | |
public function setPrice(float $price) | |
{ | |
$this->price = $price; | |
return $this; | |
} | |
/** | |
* The final price generated by the calculate function | |
* | |
* @var float | |
*/ | |
protected $final_price; | |
/** | |
* Get the value of final_price | |
* | |
* @return float | |
*/ | |
public function getFinalPrice() | |
{ | |
return $this->final_price; | |
} | |
/** | |
* Floor a value to the provided precision | |
* | |
* @param float $val the value to floor | |
* @param int $precision the decimal precision (eg 2) | |
*/ | |
protected function floorp($val, $precision) | |
{ | |
$mult = pow(10, $precision); // Can be cached in lookup table | |
return floor($val * $mult) / $mult; | |
} | |
/** | |
* Create this object and setup params | |
* | |
* @param float $price The inital price | |
* @param float $vat The rate of vat to use | |
*/ | |
public function __construct(float $price, float $vat) | |
{ | |
$this->setPrice($price); | |
$this->setVatRate($vat); | |
$this->calculate(); | |
} | |
/** | |
* Calculate the new final price, based on the submitted params and | |
* save the value. | |
*/ | |
public function calculate() | |
{ | |
$rate = $this->getVatRate(); | |
$price = $this->getPrice(); | |
$final_price = ($price / (100 + $rate)) * 100; | |
$final_price = $this->floorp($final_price, 2); | |
$this->final_price = $final_price; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment