CustomOptionPriceCalculator.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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\Catalog\Pricing\Price;
  8. use Magento\Catalog\Model\Product\Option\Value as ProductOptionValue;
  9. /**
  10. * Calculates prices of custom options of the product.
  11. */
  12. class CustomOptionPriceCalculator
  13. {
  14. /**
  15. * Calculates prices of custom option by code.
  16. *
  17. * Price is calculated depends on Price Code.
  18. * Existing logic was taken from methods \Magento\Catalog\Model\Product\Option\Value::(getPrice|getRegularPrice)
  19. * where $priceCode was hardcoded and changed to have dynamical approach.
  20. *
  21. * Examples of usage:
  22. * \Magento\Catalog\Pricing\Price\CustomOptionPrice::getValue
  23. * \Magento\Catalog\Model\Product\Option\Value::getPrice
  24. * \Magento\Catalog\Model\Product\Option\Value::getRegularPrice
  25. *
  26. * @param ProductOptionValue $optionValue
  27. * @param string $priceCode
  28. * @return float|int
  29. */
  30. public function getOptionPriceByPriceCode(
  31. ProductOptionValue $optionValue,
  32. string $priceCode = BasePrice::PRICE_CODE
  33. ) {
  34. if ($optionValue->getPriceType() === ProductOptionValue::TYPE_PERCENT) {
  35. $basePrice = $optionValue->getOption()->getProduct()->getPriceInfo()->getPrice($priceCode)->getValue();
  36. $price = $basePrice * ($optionValue->getData(ProductOptionValue::KEY_PRICE) / 100);
  37. return $price;
  38. }
  39. return $optionValue->getData(ProductOptionValue::KEY_PRICE);
  40. }
  41. }