ItemProcessor.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\InvoiceRequestBuilder;
  7. use Magento\Catalog\Api\Data\ProductInterface;
  8. use Magento\Catalog\Api\ProductRepositoryInterface;
  9. use Magento\Framework\Api\SearchCriteriaBuilder;
  10. use Magento\Framework\Api\SearchCriteriaBuilderFactory;
  11. /**
  12. * Contains logic common to processing items on Invoices and Creditmemos
  13. */
  14. class ItemProcessor
  15. {
  16. /** @var SearchCriteriaBuilderFactory */
  17. private $criteriaBuilderFactory;
  18. /** @var ProductRepositoryInterface */
  19. private $productRepository;
  20. /**
  21. * @param SearchCriteriaBuilderFactory $criteriaBuilderFactory
  22. * @param ProductRepositoryInterface $productRepository
  23. */
  24. public function __construct(
  25. SearchCriteriaBuilderFactory $criteriaBuilderFactory,
  26. ProductRepositoryInterface $productRepository
  27. ) {
  28. $this->criteriaBuilderFactory = $criteriaBuilderFactory;
  29. $this->productRepository = $productRepository;
  30. }
  31. /**
  32. * Fetch all utilized products from the database by SKU
  33. *
  34. * This was previously done by ID, but we had an issue with configurable products
  35. * in that the child did not have the total but the parent did, and the parent
  36. * was attached to the parent product. This isn't bueno, since we need
  37. * to use the child's tax class for records.
  38. *
  39. * So.. that didn't work. Instead, we're using SKU. In the vast majority
  40. * of scenarios the SKU should not change on the product.
  41. *
  42. * The correct way to "fix" this would be to attach the necessary product
  43. * data to the order, and subsequently the invoice at the time of creation,
  44. * however we'd still have a problem if that data were missing
  45. * (b/c Vertex was disabled or older versions or any number of scenarios)
  46. *
  47. * @param string[] $productSku
  48. * @return ProductInterface[] Indexed by sku
  49. */
  50. public function getProductsIndexedBySku(array $productSku)
  51. {
  52. /** @var SearchCriteriaBuilder $criteriaBuilder */
  53. $criteriaBuilder = $this->criteriaBuilderFactory->create();
  54. $criteriaBuilder->addFilter(ProductInterface::SKU, $productSku, 'in');
  55. $criteria = $criteriaBuilder->create();
  56. $items = $this->productRepository->getList($criteria)->getItems();
  57. /** @var ProductInterface[] $products */
  58. return array_reduce(
  59. $items,
  60. function (array $carry, ProductInterface $product) {
  61. $carry[$product->getSku()] = $product;
  62. return $carry;
  63. },
  64. []
  65. );
  66. }
  67. }