GetProductIdsByStockIds.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\InventoryCache\Model\ResourceModel;
  8. use Magento\Framework\App\ResourceConnection;
  9. use Magento\InventoryCatalogApi\Api\DefaultStockProviderInterface;
  10. use Magento\InventoryIndexer\Indexer\IndexStructure;
  11. use Magento\InventoryIndexer\Model\StockIndexTableNameResolverInterface;
  12. /**
  13. * Get product ids for given stock form index table.
  14. */
  15. class GetProductIdsByStockIds
  16. {
  17. /**
  18. * @var ResourceConnection
  19. */
  20. private $resource;
  21. /**
  22. * @var StockIndexTableNameResolverInterface
  23. */
  24. private $stockIndexTableNameResolver;
  25. /**
  26. * @var DefaultStockProviderInterface
  27. */
  28. private $defaultStockProvider;
  29. /**
  30. * @var string
  31. */
  32. private $productTableName;
  33. /**
  34. * @param ResourceConnection $resource
  35. * @param StockIndexTableNameResolverInterface $stockIndexTableNameResolver
  36. * @param DefaultStockProviderInterface $defaultStockProvider
  37. * @param string $productTableName
  38. */
  39. public function __construct(
  40. ResourceConnection $resource,
  41. StockIndexTableNameResolverInterface $stockIndexTableNameResolver,
  42. DefaultStockProviderInterface $defaultStockProvider,
  43. string $productTableName
  44. ) {
  45. $this->resource = $resource;
  46. $this->defaultStockProvider = $defaultStockProvider;
  47. $this->stockIndexTableNameResolver = $stockIndexTableNameResolver;
  48. $this->productTableName = $productTableName;
  49. }
  50. /**
  51. * @param array $stockIds
  52. * @return array
  53. */
  54. public function execute(array $stockIds): array
  55. {
  56. $productIds = [[]];
  57. foreach ($stockIds as $stockId) {
  58. if ($this->defaultStockProvider->getId() === (int)$stockId) {
  59. continue;
  60. }
  61. $stockIndexTableName = $this->stockIndexTableNameResolver->execute($stockId);
  62. $connection = $this->resource->getConnection();
  63. if ($connection->isTableExists($stockIndexTableName)) {
  64. $sql = $connection->select()
  65. ->from(['stock_index' => $stockIndexTableName], [])
  66. ->join(
  67. ['product' => $this->resource->getTableName($this->productTableName)],
  68. 'product.sku = stock_index.' . IndexStructure::SKU,
  69. ['product.entity_id']
  70. );
  71. $productIds[] = $connection->fetchCol($sql);
  72. }
  73. }
  74. $productIds = array_merge(...$productIds);
  75. return array_unique($productIds);
  76. }
  77. }