IndexHandler.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\InventoryIndexer\Indexer;
  8. use Magento\Framework\App\ResourceConnection;
  9. use Magento\Framework\Indexer\SaveHandler\Batch;
  10. use Magento\InventoryMultiDimensionalIndexerApi\Model\IndexHandlerInterface;
  11. use Magento\InventoryMultiDimensionalIndexerApi\Model\IndexName;
  12. use Magento\InventoryMultiDimensionalIndexerApi\Model\IndexNameResolverInterface;
  13. /**
  14. * Index handler is responsible for index data manipulation
  15. */
  16. class IndexHandler implements IndexHandlerInterface
  17. {
  18. /**
  19. * @var IndexNameResolverInterface
  20. */
  21. private $indexNameResolver;
  22. /**
  23. * @var Batch
  24. */
  25. private $batch;
  26. /**
  27. * @var ResourceConnection
  28. */
  29. private $resourceConnection;
  30. /**
  31. * @var int
  32. */
  33. private $batchSize;
  34. /**
  35. * @param IndexNameResolverInterface $indexNameResolver
  36. * @param Batch $batch
  37. * @param ResourceConnection $resourceConnection
  38. * @param int $batchSize
  39. */
  40. public function __construct(
  41. IndexNameResolverInterface $indexNameResolver,
  42. Batch $batch,
  43. ResourceConnection $resourceConnection,
  44. $batchSize
  45. ) {
  46. $this->indexNameResolver = $indexNameResolver;
  47. $this->batch = $batch;
  48. $this->resourceConnection = $resourceConnection;
  49. $this->batchSize = $batchSize;
  50. }
  51. /**
  52. * @inheritdoc
  53. */
  54. public function saveIndex(IndexName $indexName, \Traversable $documents, string $connectionName): void
  55. {
  56. $connection = $this->resourceConnection->getConnection($connectionName);
  57. $tableName = $this->indexNameResolver->resolveName($indexName);
  58. $columns = [IndexStructure::SKU, IndexStructure::QUANTITY, IndexStructure::IS_SALABLE];
  59. foreach ($this->batch->getItems($documents, $this->batchSize) as $batchDocuments) {
  60. $connection->insertArray($tableName, $columns, $batchDocuments);
  61. }
  62. }
  63. /**
  64. * @inheritdoc
  65. */
  66. public function cleanIndex(IndexName $indexName, \Traversable $documents, string $connectionName): void
  67. {
  68. $connection = $this->resourceConnection->getConnection($connectionName);
  69. $tableName = $this->indexNameResolver->resolveName($indexName);
  70. $connection->delete($tableName, ['sku IN (?)' => iterator_to_array($documents)]);
  71. }
  72. }