Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SelectBuilder.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
19 
24 {
28  private $resourceConnection;
29 
33  private $getIsStockItemSalableCondition;
34 
38  private $productTableName;
39 
45  public function __construct(
46  ResourceConnection $resourceConnection,
47  GetIsStockItemSalableConditionInterface $getIsStockItemSalableCondition,
48  string $productTableName
49  ) {
50  $this->resourceConnection = $resourceConnection;
51  $this->getIsStockItemSalableCondition = $getIsStockItemSalableCondition;
52  $this->productTableName = $productTableName;
53  }
54 
59  public function execute(int $stockId): Select
60  {
61  $connection = $this->resourceConnection->getConnection();
62  $sourceItemTable = $this->resourceConnection->getTableName(SourceItemResourceModel::TABLE_NAME_SOURCE_ITEM);
63 
64  $quantityExpression = (string)$this->resourceConnection->getConnection()->getCheckSql(
66  0,
68  );
69  $sourceCodes = $this->getSourceCodes($stockId);
70 
71  $select = $connection->select();
72  $select->joinLeft(
73  ['product' => $this->resourceConnection->getTableName($this->productTableName)],
74  'product.sku = source_item.' . SourceItemInterface::SKU,
75  []
76  )->joinLeft(
77  ['legacy_stock_item' => $this->resourceConnection->getTableName('cataloginventory_stock_item')],
78  'product.entity_id = legacy_stock_item.product_id',
79  []
80  );
81 
82  $select->from(
83  ['source_item' => $sourceItemTable],
84  [
86  IndexStructure::QUANTITY => 'SUM(' . $quantityExpression . ')',
87  IndexStructure::IS_SALABLE => $this->getIsStockItemSalableCondition->execute($select),
88  ]
89  )
90  ->where('source_item.' . SourceItemInterface::SOURCE_CODE . ' IN (?)', $sourceCodes)
91  ->group([SourceItemInterface::SKU]);
92 
93  return $select;
94  }
95 
102  private function getSourceCodes(int $stockId): array
103  {
104  $connection = $this->resourceConnection->getConnection();
105  $sourceTable = $this->resourceConnection->getTableName(SourceResourceModel::TABLE_NAME_SOURCE);
106  $sourceStockLinkTable = $this->resourceConnection->getTableName(
107  StockSourceLinkResourceModel::TABLE_NAME_STOCK_SOURCE_LINK
108  );
109 
110  $select = $connection->select()
111  ->from(['source' => $sourceTable], [SourceInterface::SOURCE_CODE])
112  ->joinInner(
113  ['stock_source_link' => $sourceStockLinkTable],
114  'source.' . SourceItemInterface::SOURCE_CODE . ' = stock_source_link.' . StockSourceLink::SOURCE_CODE,
115  []
116  )
117  ->where('stock_source_link.' . StockSourceLink::STOCK_ID . ' = ?', $stockId)
118  ->where(SourceInterface::ENABLED . ' = ?', 1);
119 
120  $sourceCodes = $connection->fetchCol($select);
121  return $sourceCodes;
122  }
123 }
__construct(ResourceConnection $resourceConnection, GetIsStockItemSalableConditionInterface $getIsStockItemSalableCondition, string $productTableName)
$connection
Definition: bulk.php:13