Collection.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Bundle\Model\ResourceModel\Selection;
  7. use Magento\Framework\DataObject;
  8. use Magento\Framework\DB\Select;
  9. use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory;
  10. use Magento\Framework\App\ObjectManager;
  11. /**
  12. * Bundle Selections Resource Collection
  13. *
  14. * @api
  15. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  16. * @since 100.0.2
  17. */
  18. class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
  19. {
  20. /**
  21. * Selection table name
  22. *
  23. * @var string
  24. */
  25. protected $_selectionTable;
  26. /**
  27. * @var DataObject
  28. */
  29. private $itemPrototype = null;
  30. /**
  31. * @var \Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor
  32. */
  33. private $catalogRuleProcessor = null;
  34. /**
  35. * Is website scope prices joined to collection
  36. *
  37. * @var bool
  38. */
  39. private $websiteScopePriceJoined = false;
  40. /**
  41. * @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item
  42. */
  43. private $stockItem;
  44. /**
  45. * Collection constructor.
  46. * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
  47. * @param \Psr\Log\LoggerInterface $logger
  48. * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
  49. * @param \Magento\Framework\Event\ManagerInterface $eventManager
  50. * @param \Magento\Eav\Model\Config $eavConfig
  51. * @param \Magento\Framework\App\ResourceConnection $resource
  52. * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory
  53. * @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper
  54. * @param \Magento\Framework\Validator\UniversalFactory $universalFactory
  55. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  56. * @param \Magento\Framework\Module\Manager $moduleManager
  57. * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState
  58. * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  59. * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory
  60. * @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl
  61. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  62. * @param \Magento\Customer\Model\Session $customerSession
  63. * @param \Magento\Framework\Stdlib\DateTime $dateTime
  64. * @param \Magento\Customer\Api\GroupManagementInterface $groupManagement
  65. * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
  66. * @param ProductLimitationFactory|null $productLimitationFactory
  67. * @param \Magento\Framework\EntityManager\MetadataPool|null $metadataPool
  68. * @param \Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer|null $tableMaintainer
  69. * @param \Magento\CatalogInventory\Model\ResourceModel\Stock\Item|null $stockItem
  70. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  71. */
  72. public function __construct(
  73. \Magento\Framework\Data\Collection\EntityFactory $entityFactory,
  74. \Psr\Log\LoggerInterface $logger,
  75. \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
  76. \Magento\Framework\Event\ManagerInterface $eventManager,
  77. \Magento\Eav\Model\Config $eavConfig,
  78. \Magento\Framework\App\ResourceConnection $resource,
  79. \Magento\Eav\Model\EntityFactory $eavEntityFactory,
  80. \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper,
  81. \Magento\Framework\Validator\UniversalFactory $universalFactory,
  82. \Magento\Store\Model\StoreManagerInterface $storeManager,
  83. \Magento\Framework\Module\Manager $moduleManager,
  84. \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState,
  85. \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  86. \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory,
  87. \Magento\Catalog\Model\ResourceModel\Url $catalogUrl,
  88. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  89. \Magento\Customer\Model\Session $customerSession,
  90. \Magento\Framework\Stdlib\DateTime $dateTime,
  91. \Magento\Customer\Api\GroupManagementInterface $groupManagement,
  92. \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
  93. ProductLimitationFactory $productLimitationFactory = null,
  94. \Magento\Framework\EntityManager\MetadataPool $metadataPool = null,
  95. \Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer $tableMaintainer = null,
  96. \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItem = null
  97. ) {
  98. parent::__construct(
  99. $entityFactory,
  100. $logger,
  101. $fetchStrategy,
  102. $eventManager,
  103. $eavConfig,
  104. $resource,
  105. $eavEntityFactory,
  106. $resourceHelper,
  107. $universalFactory,
  108. $storeManager,
  109. $moduleManager,
  110. $catalogProductFlatState,
  111. $scopeConfig,
  112. $productOptionFactory,
  113. $catalogUrl,
  114. $localeDate,
  115. $customerSession,
  116. $dateTime,
  117. $groupManagement,
  118. $connection,
  119. $productLimitationFactory,
  120. $metadataPool,
  121. $tableMaintainer
  122. );
  123. $this->stockItem = $stockItem
  124. ?? ObjectManager::getInstance()->get(\Magento\CatalogInventory\Model\ResourceModel\Stock\Item::class);
  125. }
  126. /**
  127. * Initialize collection
  128. *
  129. * @return void
  130. */
  131. protected function _construct()
  132. {
  133. parent::_construct();
  134. $this->setRowIdFieldName('selection_id');
  135. $this->_selectionTable = $this->getTable('catalog_product_bundle_selection');
  136. }
  137. /**
  138. * Set store id for each collection item when collection was loaded
  139. *
  140. * @return $this
  141. */
  142. public function _afterLoad()
  143. {
  144. return parent::_afterLoad();
  145. }
  146. /**
  147. * Initialize collection select
  148. *
  149. * @return $this|void
  150. */
  151. protected function _initSelect()
  152. {
  153. parent::_initSelect();
  154. $this->getSelect()->join(
  155. ['selection' => $this->_selectionTable],
  156. 'selection.product_id = e.entity_id',
  157. ['*']
  158. );
  159. }
  160. /**
  161. * Join website scope prices to collection, override default prices
  162. *
  163. * @param int $websiteId
  164. * @return $this
  165. */
  166. public function joinPrices($websiteId)
  167. {
  168. $connection = $this->getConnection();
  169. $priceType = $connection->getCheckSql(
  170. 'price.selection_price_type IS NOT NULL',
  171. 'price.selection_price_type',
  172. 'selection.selection_price_type'
  173. );
  174. $priceValue = $connection->getCheckSql(
  175. 'price.selection_price_value IS NOT NULL',
  176. 'price.selection_price_value',
  177. 'selection.selection_price_value'
  178. );
  179. $this->getSelect()->joinLeft(
  180. ['price' => $this->getTable('catalog_product_bundle_selection_price')],
  181. 'selection.selection_id = price.selection_id AND price.website_id = ' . (int)$websiteId .
  182. ' AND selection.parent_product_id = price.parent_product_id',
  183. [
  184. 'selection_price_type' => $priceType,
  185. 'selection_price_value' => $priceValue,
  186. 'parent_product_id' => 'price.parent_product_id',
  187. 'price_scope' => 'price.website_id'
  188. ]
  189. );
  190. $this->websiteScopePriceJoined = true;
  191. return $this;
  192. }
  193. /**
  194. * Apply option ids filter to collection
  195. *
  196. * @param array $optionIds
  197. * @return $this
  198. */
  199. public function setOptionIdsFilter($optionIds)
  200. {
  201. if (!empty($optionIds)) {
  202. $this->getSelect()->where('selection.option_id IN (?)', $optionIds);
  203. }
  204. return $this;
  205. }
  206. /**
  207. * Apply selection ids filter to collection
  208. *
  209. * @param array $selectionIds
  210. * @return $this
  211. */
  212. public function setSelectionIdsFilter($selectionIds)
  213. {
  214. if (!empty($selectionIds)) {
  215. $this->getSelect()->where('selection.selection_id IN (?)', $selectionIds);
  216. }
  217. return $this;
  218. }
  219. /**
  220. * Set position order
  221. *
  222. * @return $this
  223. */
  224. public function setPositionOrder()
  225. {
  226. $this->getSelect()->order('selection.position asc')->order('selection.selection_id asc');
  227. return $this;
  228. }
  229. /**
  230. * Add filtering of products that have 0 items left.
  231. *
  232. * @return $this
  233. * @since 100.2.0
  234. */
  235. public function addQuantityFilter()
  236. {
  237. $manageStockExpr = $this->stockItem->getManageStockExpr('stock_item');
  238. $backordersExpr = $this->stockItem->getBackordersExpr('stock_item');
  239. $minQtyExpr = $this->getConnection()->getCheckSql(
  240. 'selection.selection_can_change_qty',
  241. $this->stockItem->getMinSaleQtyExpr('stock_item'),
  242. 'selection.selection_qty'
  243. );
  244. $where = $manageStockExpr . ' = 0';
  245. $where .= ' OR ('
  246. . 'stock_item.is_in_stock = ' . \Magento\CatalogInventory\Model\Stock::STOCK_IN_STOCK
  247. . ' AND ('
  248. . $backordersExpr . ' != ' . \Magento\CatalogInventory\Model\Stock::BACKORDERS_NO
  249. . ' OR '
  250. . $minQtyExpr . ' <= stock_item.qty'
  251. . ')'
  252. . ')';
  253. $this->getSelect()
  254. ->joinInner(
  255. ['stock_item' => $this->stockItem->getMainTable()],
  256. 'selection.product_id = stock_item.product_id',
  257. []
  258. )->where($where);
  259. return $this;
  260. }
  261. /**
  262. * @inheritDoc
  263. * @since 100.2.0
  264. */
  265. public function getNewEmptyItem()
  266. {
  267. if (null === $this->itemPrototype) {
  268. $this->itemPrototype = parent::getNewEmptyItem();
  269. }
  270. return clone $this->itemPrototype;
  271. }
  272. /**
  273. * Add filter by price
  274. *
  275. * @param \Magento\Catalog\Model\Product $product
  276. * @param bool $searchMin
  277. * @param bool $useRegularPrice
  278. *
  279. * @return $this
  280. * @since 100.2.0
  281. */
  282. public function addPriceFilter($product, $searchMin, $useRegularPrice = false)
  283. {
  284. if ($product->getPriceType() == \Magento\Bundle\Model\Product\Price::PRICE_TYPE_DYNAMIC) {
  285. $this->addPriceData();
  286. if ($useRegularPrice) {
  287. $minimalPriceExpression = self::INDEX_TABLE_ALIAS . '.price';
  288. } else {
  289. $this->getCatalogRuleProcessor()->addPriceData($this, 'selection.product_id');
  290. $minimalPriceExpression = 'LEAST(minimal_price, IFNULL(catalog_rule_price, minimal_price))';
  291. }
  292. $orderByValue = new \Zend_Db_Expr(
  293. '(' .
  294. $minimalPriceExpression .
  295. ' * selection.selection_qty' .
  296. ')'
  297. );
  298. } else {
  299. $connection = $this->getConnection();
  300. $priceType = $connection->getIfNullSql(
  301. 'price.selection_price_type',
  302. 'selection.selection_price_type'
  303. );
  304. $priceValue = $connection->getIfNullSql(
  305. 'price.selection_price_value',
  306. 'selection.selection_price_value'
  307. );
  308. if (!$this->websiteScopePriceJoined) {
  309. $websiteId = $this->_storeManager->getStore()->getWebsiteId();
  310. $this->getSelect()->joinLeft(
  311. ['price' => $this->getTable('catalog_product_bundle_selection_price')],
  312. 'selection.selection_id = price.selection_id AND price.website_id = ' . (int)$websiteId,
  313. []
  314. );
  315. }
  316. $price = $connection->getCheckSql(
  317. $priceType . ' = 1',
  318. (float) $product->getPrice() . ' * '. $priceValue . ' / 100',
  319. $priceValue
  320. );
  321. $orderByValue = new \Zend_Db_Expr('('. $price. ' * '. 'selection.selection_qty)');
  322. }
  323. $this->getSelect()->reset(Select::ORDER);
  324. $this->getSelect()->order(new \Zend_Db_Expr($orderByValue . ($searchMin ? Select::SQL_ASC : Select::SQL_DESC)));
  325. $this->getSelect()->limit(1);
  326. return $this;
  327. }
  328. /**
  329. * Get Catalog Rule Processor.
  330. *
  331. * @return \Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor
  332. *
  333. * @deprecated 100.2.0
  334. */
  335. private function getCatalogRuleProcessor()
  336. {
  337. if (null === $this->catalogRuleProcessor) {
  338. $this->catalogRuleProcessor = \Magento\Framework\App\ObjectManager::getInstance()
  339. ->get(\Magento\CatalogRule\Model\ResourceModel\Product\CollectionProcessor::class);
  340. }
  341. return $this->catalogRuleProcessor;
  342. }
  343. }