Skip to content

Commit

Permalink
Merge pull request #128 from tatiana-scandi/bugfix/2463/fix-discount-…
Browse files Browse the repository at this point in the history
…zero-error

#2463 - fix zero division error during discount calculation
  • Loading branch information
carinadues authored Oct 14, 2021
2 parents cb91395 + f543147 commit 4c1551d
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions src/Model/Resolver/Product/PriceRange.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -43,7 +48,7 @@ class PriceRange extends CorePriceRange
/**
* @var PriceCurrencyInterface
*/
private PriceCurrencyInterface $priceCurrency;
protected PriceCurrencyInterface $priceCurrency;

/**
* @var ScopeConfigInterface
Expand Down Expand Up @@ -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)
];
}

Expand All @@ -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
*
Expand Down

0 comments on commit 4c1551d

Please sign in to comment.