DeltaPriceRound.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\SalesRule\Model;
  8. use Magento\Framework\Pricing\PriceCurrencyInterface;
  9. /**
  10. * Round price and save rounding operation delta.
  11. */
  12. class DeltaPriceRound
  13. {
  14. /**
  15. * @var PriceCurrencyInterface
  16. */
  17. private $priceCurrency;
  18. /**
  19. * @var float[]
  20. */
  21. private $roundingDeltas;
  22. /**
  23. * @param PriceCurrencyInterface $priceCurrency
  24. */
  25. public function __construct(PriceCurrencyInterface $priceCurrency)
  26. {
  27. $this->priceCurrency = $priceCurrency;
  28. }
  29. /**
  30. * Round price based on previous rounding operation delta.
  31. *
  32. * @param float $price
  33. * @param string $type
  34. * @return float
  35. */
  36. public function round(float $price, string $type): float
  37. {
  38. if ($price) {
  39. // initialize the delta to a small number to avoid non-deterministic behavior with rounding of 0.5
  40. $delta = isset($this->roundingDeltas[$type]) ? $this->roundingDeltas[$type] : 0.000001;
  41. $price += $delta;
  42. $roundPrice = $this->priceCurrency->round($price);
  43. $this->roundingDeltas[$type] = $price - $roundPrice;
  44. $price = $roundPrice;
  45. }
  46. return $price;
  47. }
  48. /**
  49. * Reset all deltas.
  50. *
  51. * @return void
  52. */
  53. public function resetAll(): void
  54. {
  55. $this->roundingDeltas = [];
  56. }
  57. /**
  58. * Reset deltas by type.
  59. *
  60. * @param string $type
  61. * @return void
  62. */
  63. public function reset(string $type): void
  64. {
  65. if (isset($this->roundingDeltas[$type])) {
  66. unset($this->roundingDeltas[$type]);
  67. }
  68. }
  69. }