diff --git a/src/Model/Resolver/Product/PriceRange.php b/src/Model/Resolver/Product/PriceRange.php index 0b5e220..c93fbb8 100644 --- a/src/Model/Resolver/Product/PriceRange.php +++ b/src/Model/Resolver/Product/PriceRange.php @@ -30,6 +30,11 @@ class PriceRange extends CorePriceRange { const XML_PRICE_INCLUDES_TAX = 'tax/calculation/price_includes_tax'; + /** + * @var float + */ + protected $zeroThreshold = 0.0001; + /** * @var Discount */ @@ -43,7 +48,7 @@ class PriceRange extends CorePriceRange /** * @var PriceCurrencyInterface */ - private PriceCurrencyInterface $priceCurrency; + protected PriceCurrencyInterface $priceCurrency; /** * @var ScopeConfigInterface @@ -267,8 +272,8 @@ protected function calculateDiscount(Product $product, float $regularPrice, floa $priceDifference = $regularPrice - $finalPrice; return [ - 'amount_off' => round($priceDifference, 2), - 'percent_off' => round($priceDifference / $regularPrice * 100, 8) + 'amount_off' => $this->getPriceDifferenceAsValue($regularPrice, $finalPrice), + 'percent_off' => $this->getPriceDifferenceAsPercent($regularPrice, $finalPrice) ]; } @@ -282,6 +287,41 @@ protected function calculateDiscount(Product $product, float $regularPrice, floa ]; } + /** + * Get value difference between two prices + * + * @param float $regularPrice + * @param float $finalPrice + * @return float + */ + protected function getPriceDifferenceAsValue(float $regularPrice, float $finalPrice) + { + $difference = $regularPrice - $finalPrice; + if ($difference <= $this->zeroThreshold) { + return 0; + } + + return round($difference, 2); + } + + /** + * Get percent difference between two prices + * + * @param float $regularPrice + * @param float $finalPrice + * @return float + */ + protected function getPriceDifferenceAsPercent(float $regularPrice, float $finalPrice) + { + $difference = $this->getPriceDifferenceAsValue($regularPrice, $finalPrice); + + if ($difference <= $this->zeroThreshold || $regularPrice <= $this->zeroThreshold) { + return 0; + } + + return round(($difference / $regularPrice) * 100, 8); + } + /** * Gets [active] special price value *