LineItemBuilder.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Api\Data;
  7. use Magento\Tax\Api\Data\QuoteDetailsItemInterface;
  8. use Magento\Tax\Api\Data\TaxClassKeyInterface;
  9. use Vertex\Data\LineItemInterface;
  10. use Vertex\Data\LineItemInterfaceFactory;
  11. use Vertex\Tax\Model\Config;
  12. use Vertex\Tax\Model\Repository\TaxClassNameRepository;
  13. /**
  14. * Builds a {@see LineItemInterface} for use with the Vertex SDK
  15. */
  16. class LineItemBuilder
  17. {
  18. /** @var LineItemInterfaceFactory */
  19. private $factory;
  20. /** @var TaxClassNameRepository */
  21. private $taxClassNameRepository;
  22. /**
  23. * @param TaxClassNameRepository $taxClassNameRepository
  24. * @param LineItemInterfaceFactory $factory
  25. */
  26. public function __construct(
  27. TaxClassNameRepository $taxClassNameRepository,
  28. LineItemInterfaceFactory $factory
  29. ) {
  30. $this->taxClassNameRepository = $taxClassNameRepository;
  31. $this->factory = $factory;
  32. }
  33. /**
  34. * Build a {@see LineItemInterface} from a {@see QuoteDetailsItemInterface}
  35. *
  36. * @param QuoteDetailsItemInterface $item
  37. * @param int|null $qtyOverride
  38. * @return LineItemInterface
  39. */
  40. public function buildFromQuoteDetailsItem(QuoteDetailsItemInterface $item, $qtyOverride = null)
  41. {
  42. $lineItem = $this->createLineItem();
  43. $sku = $item->getExtensionAttributes() !== null
  44. ? $item->getExtensionAttributes()->getVertexProductCode()
  45. : null;
  46. if ($sku !== null) {
  47. $lineItem->setProductCode(substr($sku, 0, Config::MAX_CHAR_PRODUCT_CODE_ALLOWED));
  48. }
  49. $taxClassId = $item->getTaxClassKey() && $item->getTaxClassKey()->getType() === TaxClassKeyInterface::TYPE_ID
  50. ? $item->getTaxClassKey()->getValue()
  51. : $item->getTaxClassId();
  52. $lineItem->setProductClass(
  53. $this->taxClassNameRepository->getById($taxClassId)
  54. );
  55. $quantity = (float)($qtyOverride ?: $item->getQuantity());
  56. $lineItem->setQuantity($quantity);
  57. $lineItem->setUnitPrice($item->getUnitPrice());
  58. $rowTotal = $item->getUnitPrice() * $quantity;
  59. $lineItem->setExtendedPrice($rowTotal - $item->getDiscountAmount());
  60. $lineItem->setLineItemId($item->getCode());
  61. return $lineItem;
  62. }
  63. /**
  64. * Create a {@see LineItemInterface}
  65. *
  66. * @return LineItemInterface
  67. */
  68. private function createLineItem()
  69. {
  70. return $this->factory->create();
  71. }
  72. }