ItemKeyManager.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * @copyright Vertex. All rights reserved. https://www.vertexinc.com/
  4. * @author Mediotype https://www.mediotype.com/
  5. */
  6. namespace Vertex\Tax\Model\Calculation\VertexCalculator;
  7. use Vertex\Tax\Model\Calculation\VertexCalculator;
  8. use Vertex\Tax\Model\TaxRegistry;
  9. use Magento\Tax\Api\Data\QuoteDetailsItemInterface;
  10. use Magento\Quote\Model\Quote\Item\AbstractItem;
  11. /**
  12. * Storage utility for item-level tax information that persists across a tax calculation cycle.
  13. */
  14. class ItemKeyManager
  15. {
  16. /** @var TaxRegistry */
  17. private $taxRegistry;
  18. /**
  19. * @param TaxRegistry $taxRegistry
  20. */
  21. public function __construct(TaxRegistry $taxRegistry)
  22. {
  23. $this->taxRegistry = $taxRegistry;
  24. }
  25. /**
  26. * Generate a unique ID for the given quote item.
  27. *
  28. * @param AbstractItem $item
  29. * @return string
  30. */
  31. public function createQuoteItemHash(AbstractItem $item)
  32. {
  33. return sha1(
  34. $item->getId()
  35. . $item->getQuoteId()
  36. . $item->getProductId()
  37. . $item->getQty()
  38. );
  39. }
  40. /**
  41. * Retrieve the key for the given item.
  42. *
  43. * @param QuoteDetailsItemInterface $item
  44. * @return string|null
  45. */
  46. public function get(QuoteDetailsItemInterface $item)
  47. {
  48. return $this->taxRegistry->lookup($this->generateItemStorageKey($item));
  49. }
  50. /**
  51. * Write the given quote item ID to storage.
  52. *
  53. * @param QuoteDetailsItemInterface $item
  54. * @param AbstractItem $quoteItem
  55. * @return void
  56. */
  57. public function set(QuoteDetailsItemInterface $item, AbstractItem $quoteItem)
  58. {
  59. $cacheKey = $this->generateItemStorageKey($item);
  60. $this->taxRegistry->unregister($cacheKey);
  61. $this->taxRegistry->register($cacheKey, $this->createQuoteItemHash($quoteItem));
  62. }
  63. /**
  64. * Generate a unique storage key for the given item.
  65. *
  66. * @param QuoteDetailsItemInterface $item
  67. * @return string
  68. */
  69. private function generateItemStorageKey(QuoteDetailsItemInterface $item)
  70. {
  71. return sha1(
  72. VertexCalculator::VERTEX_QUOTE_ITEM_ID_PREFIX
  73. . $item->getCode()
  74. . $item->getParentCode()
  75. . $item->getType()
  76. );
  77. }
  78. }