UpdateProductOptionsObserver.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Tax\Observer;
  7. use Magento\Framework\Event\ObserverInterface;
  8. class UpdateProductOptionsObserver implements ObserverInterface
  9. {
  10. /**
  11. * Tax data
  12. *
  13. * @var \Magento\Tax\Helper\Data
  14. */
  15. protected $taxData;
  16. /**
  17. * @var \Magento\Framework\Registry
  18. */
  19. protected $registry;
  20. /**
  21. * @param \Magento\Tax\Helper\Data $taxData
  22. * @param \Magento\Framework\Registry $registry
  23. */
  24. public function __construct(
  25. \Magento\Tax\Helper\Data $taxData,
  26. \Magento\Framework\Registry $registry
  27. ) {
  28. $this->taxData = $taxData;
  29. $this->registry = $registry;
  30. }
  31. /**
  32. * Change default JavaScript templates for options rendering
  33. *
  34. * @param \Magento\Framework\Event\Observer $observer
  35. * @return $this
  36. */
  37. public function execute(\Magento\Framework\Event\Observer $observer)
  38. {
  39. $response = $observer->getEvent()->getResponseObject();
  40. $options = $response->getAdditionalOptions();
  41. $_product = $this->registry->registry('current_product');
  42. if (!$_product) {
  43. return $this;
  44. }
  45. $algorithm = $this->taxData->getCalculationAlgorithm();
  46. $options['calculationAlgorithm'] = $algorithm;
  47. // prepare correct template for options render
  48. if ($this->taxData->displayBothPrices()) {
  49. $options['optionTemplate'] = sprintf(
  50. '<%%= data.label %%>'
  51. . '<%% if (data.finalPrice.value) { %%>'
  52. . ' +<%%= data.finalPrice.formatted %%> (%1$s <%%= data.basePrice.formatted %%>)'
  53. . '<%% } %%>',
  54. __('Excl. tax:')
  55. );
  56. } elseif ($this->taxData->priceIncludesTax() && $this->taxData->displayPriceExcludingTax()) {
  57. $options['optionTemplate'] = sprintf(
  58. '<%%= data.label %%>'
  59. . '<%% if (data.basePrice.value) { %%>'
  60. . ' +<%%= data.basePrice.formatted %%>'
  61. . '<%% } %%>'
  62. );
  63. }
  64. $response->setAdditionalOptions($options);
  65. return $this;
  66. }
  67. }