Calculator.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Pricing\Adjustment;
  7. use Magento\Framework\Pricing\Amount\AmountFactory;
  8. use Magento\Framework\Pricing\SaleableInterface;
  9. /**
  10. * Class Calculator
  11. */
  12. class Calculator implements CalculatorInterface
  13. {
  14. /**
  15. * @var AmountFactory
  16. */
  17. protected $amountFactory;
  18. /**
  19. * @param AmountFactory $amountFactory
  20. */
  21. public function __construct(AmountFactory $amountFactory)
  22. {
  23. $this->amountFactory = $amountFactory;
  24. }
  25. /**
  26. * Retrieve Amount object based on given float amount, product and exclude option.
  27. * It is possible to pass "true" or adjustment code to exclude all or specific adjustment from an amount.
  28. *
  29. * @param float|string $amount
  30. * @param SaleableInterface $saleableItem
  31. * @param null|bool|string|array $exclude
  32. * @param null|array $context
  33. * @return \Magento\Framework\Pricing\Amount\AmountInterface
  34. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  35. */
  36. public function getAmount($amount, SaleableInterface $saleableItem, $exclude = null, $context = [])
  37. {
  38. $baseAmount = $fullAmount = $amount;
  39. $previousAdjustments = 0;
  40. $adjustments = [];
  41. foreach ($saleableItem->getPriceInfo()->getAdjustments() as $adjustment) {
  42. $code = $adjustment->getAdjustmentCode();
  43. $toExclude = false;
  44. if (!is_array($exclude)) {
  45. if ($exclude === true || ($exclude !== null && $code === $exclude)) {
  46. $toExclude = true;
  47. }
  48. } else {
  49. if (in_array($code, $exclude)) {
  50. $toExclude = true;
  51. }
  52. }
  53. if ($adjustment->isIncludedInBasePrice()) {
  54. $adjust = $adjustment->extractAdjustment($baseAmount, $saleableItem, $context);
  55. $baseAmount -= $adjust;
  56. $fullAmount = $adjustment->applyAdjustment($fullAmount, $saleableItem, $context);
  57. $adjust = $fullAmount - $baseAmount - $previousAdjustments;
  58. if (!$toExclude) {
  59. $adjustments[$code] = $adjust;
  60. }
  61. } elseif ($adjustment->isIncludedInDisplayPrice($saleableItem)) {
  62. if ($toExclude) {
  63. continue;
  64. }
  65. $newAmount = $adjustment->applyAdjustment($fullAmount, $saleableItem, $context);
  66. $adjust = $newAmount - $fullAmount;
  67. $adjustments[$code] = $adjust;
  68. $fullAmount = $newAmount;
  69. $previousAdjustments += $adjust;
  70. }
  71. }
  72. return $this->amountFactory->create($fullAmount, $adjustments);
  73. }
  74. }