/** * @param \Magento\Catalog\Model\Category $category * @return \Magento\Catalog\Model\Resource\Product\Collection */ public function getCollection(\Magento\Catalog\Model\Category $category) { /** @var \Magento\Catalog\Model\Resource\Product\Collection $collection */ $collection = $this->collectionFactory->create(); $collection->addCategoryFilter($category); return $collection; }
/** * Construct * * @param string $name * @param string $primaryFieldName * @param string $requestFieldName * @param CollectionFactory $collectionFactory * @param \Magento\Ui\DataProvider\AddFieldToCollectionInterface[] $addFieldStrategies * @param \Magento\Ui\DataProvider\AddFilterToCollectionInterface[] $addFilterStrategies * @param array $meta * @param array $data */ public function __construct($name, $primaryFieldName, $requestFieldName, CollectionFactory $collectionFactory, array $addFieldStrategies = [], array $addFilterStrategies = [], array $meta = [], array $data = []) { parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data); $this->collection = $collectionFactory->create(); $this->addFieldStrategies = $addFieldStrategies; $this->addFilterStrategies = $addFilterStrategies; }
/** * @param FixtureHelper $fixtureHelper * @param CsvReaderFactory $csvReaderFactory * @param \Magento\Catalog\Model\Resource\Product\CollectionFactory $productCollectionFactory * @param \Magento\SampleData\Model\Logger $logger * @param \Magento\Framework\App\Config\Storage\WriterInterface $configWriter */ public function __construct(FixtureHelper $fixtureHelper, CsvReaderFactory $csvReaderFactory, \Magento\Catalog\Model\Resource\Product\CollectionFactory $productCollectionFactory, \Magento\SampleData\Model\Logger $logger, \Magento\Framework\App\Config\Storage\WriterInterface $configWriter) { $this->fixtureHelper = $fixtureHelper; $this->csvReaderFactory = $csvReaderFactory; $this->productCollection = $productCollectionFactory->create()->addAttributeToSelect('sku'); $this->logger = $logger; $this->configWriter = $configWriter; }
/** * @param \Magento\Review\Model\ReviewFactory $reviewFactory * @param FixtureHelper $fixtureHelper * @param CsvReaderFactory $csvReaderFactory * @param \Magento\Review\Model\RatingFactory $ratingFactory * @param \Magento\Catalog\Model\Resource\Product\CollectionFactory $productCollectionFactory * @param CustomerRepositoryInterface $customerAccount * @param \Magento\SampleData\Model\Logger $logger * @param \Magento\Review\Model\Rating\OptionFactory $ratingOptionsFactory * @param \Magento\SampleData\Helper\StoreManager $storeManager */ public function __construct(\Magento\Review\Model\ReviewFactory $reviewFactory, FixtureHelper $fixtureHelper, CsvReaderFactory $csvReaderFactory, \Magento\Review\Model\RatingFactory $ratingFactory, \Magento\Catalog\Model\Resource\Product\CollectionFactory $productCollectionFactory, CustomerRepositoryInterface $customerAccount, \Magento\SampleData\Model\Logger $logger, \Magento\Review\Model\Rating\OptionFactory $ratingOptionsFactory, \Magento\SampleData\Helper\StoreManager $storeManager) { $this->reviewFactory = $reviewFactory; $this->fixtureHelper = $fixtureHelper; $this->csvReaderFactory = $csvReaderFactory; $this->ratingFactory = $ratingFactory; $this->productCollection = $productCollectionFactory->create()->addAttributeToSelect('sku'); $this->logger = $logger; $this->customerRepository = $customerAccount; $this->ratingOptionsFactory = $ratingOptionsFactory; $this->storeManager = $storeManager; }
/** * @return \Magento\Catalog\Model\Resource\Product\Collection */ protected function _getProductCollection() { if (is_null($this->_productCollection)) { /** @var \Magento\Catalog\Model\Resource\Product\Collection $collection */ $collection = $this->_productCollectionFactory->create(); $this->_layerFactory->create()->prepareProductCollection($collection); $collection->getSelect()->order('rand()'); $collection->addStoreFilter(); $numProducts = $this->getNumProducts() ? $this->getNumProducts() : 0; $collection->setPage(1, $numProducts); $this->_productCollection = $collection; } return $this->_productCollection; }
/** * @param \Magento\Catalog\Model\Category $category * @param int $storeId * @return $this */ public function getProductCollection(\Magento\Catalog\Model\Category $category, $storeId) { /** @var $layer \Magento\Catalog\Model\Layer */ $layer = $this->catalogLayer->setStore($storeId); $collection = $category->getResourceCollection(); $collection->addAttributeToSelect('url_key')->addAttributeToSelect('name')->addAttributeToSelect('is_anchor')->addAttributeToFilter('is_active', 1)->addIdFilter($category->getChildren())->load(); /** @var $productCollection \Magento\Catalog\Model\Resource\Product\Collection */ $productCollection = $this->collectionFactory->create(); $currentCategory = $layer->setCurrentCategory($category); $layer->prepareProductCollection($productCollection); $productCollection->addCountToCategories($collection); $category->getProductCollection()->setStoreId($storeId); $products = $currentCategory->getProductCollection()->addAttributeToSort('updated_at', 'desc')->setVisibility($this->visibility->getVisibleInCatalogIds())->setCurPage(1)->setPageSize(50); return $products; }
/** * {@inheritdoc} */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) { /** @var \Magento\Catalog\Model\Resource\Product\Collection $collection */ $collection = $this->collectionFactory->create(); $defaultAttributeSetId = $this->eavConfig->getEntityType(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE)->getDefaultAttributeSetId(); $extendedSearchCriteria = $this->searchCriteriaBuilder->addFilter([$this->filterBuilder->setField('attribute_set_id')->setValue($defaultAttributeSetId)->create()]); foreach ($this->metadataService->getList($extendedSearchCriteria->create())->getItems() as $metadata) { $collection->addAttributeToSelect($metadata->getAttributeCode()); } $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner'); $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner'); //Add filters from root filter group to the collection foreach ($searchCriteria->getFilterGroups() as $group) { $this->addFilterGroupToCollection($group, $collection); } /** @var SortOrder $sortOrder */ foreach ((array) $searchCriteria->getSortOrders() as $sortOrder) { $field = $sortOrder->getField(); $collection->addOrder($field, $sortOrder->getDirection() == SearchCriteriaInterface::SORT_ASC ? 'ASC' : 'DESC'); } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); $collection->load(); $searchResult = $this->searchResultsFactory->create(); $searchResult->setSearchCriteria($searchCriteria); $searchResult->setItems($collection->getItems()); $searchResult->setTotalCount($collection->getSize()); return $searchResult; }
/** * Test public `createCollection` method and protected `getPageSize` method via `createCollection` * * @param bool $pagerEnable * @param int $productsCount * @param int $productsPerPage * @param int $expectedPageSize * @dataProvider createCollectionDataProvider */ public function testCreateCollection($pagerEnable, $productsCount, $productsPerPage, $expectedPageSize) { $this->visibility->expects($this->once())->method('getVisibleInCatalogIds')->willReturn([Visibility::VISIBILITY_IN_CATALOG, Visibility::VISIBILITY_BOTH]); $collection = $this->getMockBuilder('\\Magento\\Catalog\\Model\\Resource\\Product\\Collection')->setMethods(['setVisibility', 'addMinimalPrice', 'addFinalPrice', 'addTaxPercents', 'addAttributeToSelect', 'addUrlRewrite', 'addStoreFilter', 'setPageSize', 'setCurPage'])->disableOriginalConstructor()->getMock(); $collection->expects($this->once())->method('setVisibility')->with([Visibility::VISIBILITY_IN_CATALOG, Visibility::VISIBILITY_BOTH])->willReturnSelf(); $collection->expects($this->once())->method('addMinimalPrice')->willReturnSelf(); $collection->expects($this->once())->method('addFinalPrice')->willReturnSelf(); $collection->expects($this->once())->method('addTaxPercents')->willReturnSelf(); $collection->expects($this->once())->method('addAttributeToSelect')->willReturnSelf(); $collection->expects($this->once())->method('addUrlRewrite')->willReturnSelf(); $collection->expects($this->once())->method('addStoreFilter')->willReturnSelf(); $collection->expects($this->once())->method('setPageSize')->with($expectedPageSize)->willReturnSelf(); $collection->expects($this->once())->method('setCurPage')->willReturnSelf(); $this->collectionFactory->expects($this->once())->method('create')->willReturn($collection); $this->productsList->setData('conditions_encoded', 'some_serialized_conditions'); $conditions = $this->getMockBuilder('\\Magento\\Rule\\Model\\Condition\\Combine')->setMethods(['collectValidatedAttributes'])->disableOriginalConstructor()->getMock(); $conditions->expects($this->once())->method('collectValidatedAttributes')->with($collection)->willReturnSelf(); $this->builder->expects($this->once())->method('attachConditionToCollection')->with($collection, $conditions)->willReturnSelf(); $this->rule->expects($this->once())->method('loadPost')->willReturnSelf(); $this->rule->expects($this->once())->method('getConditions')->willReturn($conditions); if ($productsPerPage) { $this->productsList->setData('products_per_page', $productsPerPage); } else { $this->productsList->unsetData('products_per_page'); } $this->productsList->setData('show_pager', $pagerEnable); $this->productsList->setData('products_count', $productsCount); $this->assertSame($collection, $this->productsList->createCollection()); }
/** * {@inheritdoc} * Example of request: * { * "searchCriteria": { * "filterGroups": [ * { * "filters": [ * {"value": "16.000", "conditionType" : "eq", "field" : "price"} * ] * } * ] * }, * "sort_orders" : {"id": "1"}, * "page_size" : "30", * "current_page" : "10" * } * * products?searchCriteria[filterGroups][0][filters][0][field]=price& * searchCriteria[filterGroups][0][filters][0][value]=16.000&page_size=30¤t_page=1&sort_orders[id]=1 */ public function search(SearchCriteria $searchCriteria) { $this->searchResultsBuilder->setSearchCriteria($searchCriteria); /** @var \Magento\Catalog\Model\Resource\Product\Collection $collection */ $collection = $this->productCollection->create(); // This is needed to make sure all the attributes are properly loaded foreach ($this->metadataService->getProductAttributesMetadata() as $metadata) { $collection->addAttributeToSelect($metadata->getAttributeCode()); } $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner'); $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner'); //Add filters from root filter group to the collection foreach ($searchCriteria->getFilterGroups() as $group) { $this->addFilterGroupToCollection($group, $collection); } /** @var SortOrder $sortOrder*/ foreach ((array) $searchCriteria->getSortOrders() as $sortOrder) { $field = $this->translateField($sortOrder->getField()); $collection->addOrder($field, $sortOrder->getDirection() == SearchCriteria::SORT_ASC ? 'ASC' : 'DESC'); } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); $products = array(); /** @var \Magento\Catalog\Model\Product $productModel */ foreach ($collection as $productModel) { $products[] = $this->converter->createProductDataFromModel($productModel); } $this->searchResultsBuilder->setItems($products); $this->searchResultsBuilder->setTotalCount($collection->getSize()); return $this->searchResultsBuilder->create(); }
/** * Get catalog product resource collection instance * * @return \Magento\Catalog\Model\Resource\Product\Collection */ protected function _getCpCollectionInstance() { if (!$this->_cpCollectionInstance) { $this->_cpCollectionInstance = $this->_cpCollection->create(); } return $this->_cpCollectionInstance; }
/** * Retrieve child categories of current category * * @return \Magento\Framework\Data\Tree\Node\Collection */ public function getCurrentChildCategories() { $categories = $this->_catalogLayer->getCurrentCategory()->getChildrenCategories(); /** @var \Magento\Catalog\Model\Resource\Product\Collection $productCollection */ $productCollection = $this->_productCollectionFactory->create(); $this->_catalogLayer->prepareProductCollection($productCollection); $productCollection->addCountToCategories($categories); return $categories; }
/** * Prepare and return product collection * * @return \Magento\Catalog\Model\Resource\Product\Collection|Object|\Magento\Framework\Data\Collection */ protected function _getProductCollection() { $todayStartOfDayDate = $this->_localeDate->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s'); $todayEndOfDayDate = $this->_localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s'); /** @var $collection \Magento\Catalog\Model\Resource\Product\Collection */ $collection = $this->_productCollectionFactory->create(); $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds()); $collection = $this->_addProductAttributesAndPrices($collection)->addStoreFilter()->addAttributeToFilter('news_from_date', ['or' => [0 => ['date' => true, 'to' => $todayEndOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter('news_to_date', ['or' => [0 => ['date' => true, 'from' => $todayStartOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter([['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')], ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')]])->addAttributeToSort('news_from_date', 'desc')->setPageSize($this->getProductsCount())->setCurPage(1); return $collection; }
/** * Prepare and return product collection * * @return \Magento\Catalog\Model\Resource\Product\Collection|Object|\Magento\Framework\Data\Collection */ protected function _getProductCollection() { $todayStartOfDayDate = $this->_localeDate->date()->setTime('00:00:00')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $todayEndOfDayDate = $this->_localeDate->date()->setTime('23:59:59')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); /** @var $collection \Magento\Catalog\Model\Resource\Product\Collection */ $collection = $this->_productCollectionFactory->create(); $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds()); $collection = $this->_addProductAttributesAndPrices($collection)->addStoreFilter()->addAttributeToFilter('news_from_date', array('or' => array(0 => array('date' => true, 'to' => $todayEndOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter('news_to_date', array('or' => array(0 => array('date' => true, 'from' => $todayStartOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter(array(array('attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')), array('attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null'))))->addAttributeToSort('news_from_date', 'desc')->setPageSize($this->getProductsCount())->setCurPage(1); return $collection; }
/** * Prepare and return product collection * * @return \Magento\Catalog\Model\Resource\Product\Collection */ public function createCollection() { /** @var $collection \Magento\Catalog\Model\Resource\Product\Collection */ $collection = $this->productCollectionFactory->create(); $collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds()); $collection = $this->_addProductAttributesAndPrices($collection)->addStoreFilter()->setPageSize($this->getProductsPerPage())->setCurPage($this->getRequest()->getParam(self::PAGE_VAR_NAME, 1)); $conditions = $this->getConditions(); $conditions->collectValidatedAttributes($collection); $this->sqlBuilder->attachConditionToCollection($collection, $conditions); return $collection; }
/** * Return product collection with selected product filter * Product collection didn't load * * @return \Magento\Catalog\Model\Resource\Product\Collection */ public function getProducts() { if ($this->_products === null) { $productsIds = $this->getProductIds(); if (!is_array($productsIds)) { $productsIds = [0]; } $this->_products = $this->_productsFactory->create()->setStoreId($this->getSelectedStoreId())->addIdFilter($productsIds); } return $this->_products; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function setUp() { $this->setCollectionFactory = $this->getMock('Magento\\Eav\\Model\\Resource\\Entity\\Attribute\\Set\\CollectionFactory', ['create'], [], '', false); $this->setCollection = $this->getMock('Magento\\Eav\\Model\\Resource\\Entity\\Attribute\\Set\\Collection', ['setEntityTypeFilter'], [], '', false); $this->setCollectionFactory->expects($this->any())->method('create')->will($this->returnValue($this->setCollection)); $item = new \Magento\Framework\Object(['id' => 1, 'attribute_set_name' => 'Default', '_attribute_set' => 'Default']); $this->setCollection->expects($this->any())->method('setEntityTypeFilter')->will($this->returnValue([$item])); $this->attrCollectionFactory = $this->getMock('Magento\\Catalog\\Model\\Resource\\Product\\Attribute\\CollectionFactory', ['create'], [], '', false); $this->attrCollection = $this->getMock('\\Magento\\Catalog\\Model\\Resource\\Product\\Attribute\\Collection', ['setAttributeSetFilter'], [], '', false); $superAttributes = []; foreach ($this->_getSuperAttributes() as $superAttribute) { $item = $this->getMock('\\Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute', ['isStatic'], $superAttribute, '', false); $item->setData($superAttribute); $item->method('isStatic')->will($this->returnValue(false)); $superAttributes[] = $item; } $this->attrCollectionFactory->expects($this->any())->method('create')->will($this->returnValue($this->attrCollection)); $this->attrCollection->expects($this->any())->method('setAttributeSetFilter')->will($this->returnValue($superAttributes)); $this->_entityModel = $this->getMock('Magento\\CatalogImportExport\\Model\\Import\\Product', ['getNewSku', 'getOldSku', 'getNextBunch', 'isRowAllowedToImport', 'getConnection', 'getAttrSetIdToName', 'getAttributeOptions'], [], '', false); $this->params = [0 => $this->_entityModel, 1 => 'configurable']; $this->objectManagerHelper = new ObjectManagerHelper($this); $this->_connection = $this->getMock('Magento\\Framework\\DB\\Adapter\\Pdo\\Mysql', ['select', 'fetchAll', 'fetchPairs', 'joinLeft', 'insertOnDuplicate', 'delete', 'quoteInto'], [], '', false); $this->select = $this->getMock('Magento\\Framework\\DB\\Select', ['from', 'where', 'joinLeft', 'getAdapter'], [], '', false); $this->select->expects($this->any())->method('from')->will($this->returnSelf()); $this->select->expects($this->any())->method('where')->will($this->returnSelf()); $this->select->expects($this->any())->method('joinLeft')->will($this->returnSelf()); $this->_connection->expects($this->any())->method('select')->will($this->returnValue($this->select)); $adapter = $this->getMock('Magento\\Framework\\DB\\Adapter\\Pdo\\Mysql', [], [], '', false); $adapter->expects($this->any())->method('quoteInto')->will($this->returnValue('query')); $this->select->expects($this->any())->method('getAdapter')->willReturn($adapter); $this->_connection->expects($this->any())->method('insertOnDuplicate')->willReturnSelf(); $this->_connection->expects($this->any())->method('delete')->willReturnSelf(); $this->_connection->expects($this->any())->method('quoteInto')->willReturn(''); $this->_connection->expects($this->any())->method('fetchPairs')->will($this->returnValue([])); $this->resource = $this->getMock('\\Magento\\Framework\\App\\Resource', ['getConnection', 'getTableName'], [], '', false); $this->resource->expects($this->any())->method('getConnection')->will($this->returnValue($this->_connection)); $this->resource->expects($this->any())->method('getTableName')->will($this->returnValue('tableName')); $this->_entityModel->expects($this->any())->method('getConnection')->will($this->returnValue($this->_connection)); $this->productCollectionFactory = $this->getMock('\\Magento\\Catalog\\Model\\Resource\\Product\\CollectionFactory', ['create'], [], '', false); $this->productCollection = $this->getMock('\\Magento\\Catalog\\Model\\Resource\\Product\\Collection', ['addFieldToFilter', 'addAttributeToSelect'], [], '', false); $products = []; $testProducts = [['id' => 1, 'attribute_set_id' => 4, 'testattr2' => 1, 'testattr3' => 1], ['id' => 2, 'attribute_set_id' => 4, 'testattr2' => 1, 'testattr3' => 1], ['id' => 20, 'attribute_set_id' => 4, 'testattr2' => 1, 'testattr3' => 1]]; foreach ($testProducts as $product) { $item = $this->getMock('\\Magento\\Framework\\Object', ['getAttributeSetId'], [], '', false); $item->setData($product); $item->expects($this->any())->method('getAttributeSetId')->willReturn(4); $products[] = $item; } $this->productCollectionFactory->expects($this->any())->method('create')->will($this->returnValue($this->productCollection)); $this->productCollection->expects($this->any())->method('addFieldToFilter')->will($this->returnValue($this->productCollection)); $this->productCollection->expects($this->any())->method('addAttributeToSelect')->will($this->returnValue($products)); $this->_entityModel->expects($this->any())->method('getAttributeOptions')->will($this->returnValue(['attr2val1' => '1', 'attr2val2' => '2', 'attr2val3' => '3', 'testattr3v1' => '4', 'testattr30v1' => '4', 'testattr3v2' => '5', 'testattr3v3' => '6'])); $this->configurable = $this->objectManagerHelper->getObject('Magento\\ConfigurableImportExport\\Model\\Import\\Product\\Type\\Configurable', ['attrSetColFac' => $this->setCollectionFactory, 'prodAttrColFac' => $this->attrCollectionFactory, 'params' => $this->params, 'resource' => $this->resource, 'productColFac' => $this->productCollectionFactory]); }
/** * @param string $matchValue * @return array */ protected function matcherProduct($matchValue) { $replaceData = []; $productCollection = $this->productCollectionFactory->create(); $productItem = $productCollection->addAttributeToFilter('sku', $matchValue)->addUrlRewrite()->getFirstItem(); $productUrl = null; if ($productItem) { $productUrl = '{{store url=""}}' . $productItem->getRequestPath(); } $replaceData['regexp'][] = '/{{product sku="' . $matchValue . '"}}/'; $replaceData['value'][] = $productUrl; return $replaceData; }
/** * Add products to items and item options * * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _assignProducts() { \Magento\Framework\Profiler::start('QUOTE:' . __METHOD__, ['group' => 'QUOTE', 'method' => __METHOD__]); $productIds = []; foreach ($this as $item) { $productIds[] = (int) $item->getProductId(); } $this->_productIds = array_merge($this->_productIds, $productIds); $productCollection = $this->_productCollectionFactory->create()->setStoreId($this->getStoreId())->addIdFilter($this->_productIds)->addAttributeToSelect($this->_quoteConfig->getProductAttributes())->addOptionsToResult()->addStoreFilter()->addUrlRewrite()->addTierPriceData(); $this->_eventManager->dispatch('prepare_catalog_product_collection_prices', ['collection' => $productCollection, 'store_id' => $this->getStoreId()]); $this->_eventManager->dispatch('sales_quote_item_collection_products_after_load', ['product_collection' => $productCollection]); $recollectQuote = false; foreach ($this as $item) { $product = $productCollection->getItemById($item->getProductId()); if ($product) { $product->setCustomOptions([]); $qtyOptions = []; $optionProductIds = []; foreach ($item->getOptions() as $option) { /** * Call type-specific logic for product associated with quote item */ $product->getTypeInstance()->assignProductToOption($productCollection->getItemById($option->getProductId()), $option, $product); if (is_object($option->getProduct()) && $option->getProduct()->getId() != $product->getId()) { $optionProductIds[$option->getProduct()->getId()] = $option->getProduct()->getId(); } } if ($optionProductIds) { foreach ($optionProductIds as $optionProductId) { $qtyOption = $item->getOptionByCode('product_qty_' . $optionProductId); if ($qtyOption) { $qtyOptions[$optionProductId] = $qtyOption; } } } $item->setQtyOptions($qtyOptions)->setProduct($product); } else { $item->isDeleted(true); $recollectQuote = true; } $item->checkData(); } if ($recollectQuote && $this->_quote) { $this->_quote->collectTotals(); } \Magento\Framework\Profiler::stop('QUOTE:' . __METHOD__); return $this; }
/** * prepare the collection * @return $this */ protected function _prepareCollection() { $collection = $this->productCollectionFactory->create(); $collection->addAttributeToSelect('price'); $adminStore = Store::DEFAULT_STORE_ID; $collection->joinAttribute('product_name', 'catalog_product/name', 'entity_id', null, 'left', $adminStore); $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'left', $adminStore); $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'left', $adminStore); if ($this->getAuthor()->getId()) { $constraint = '{{table}}.author_id=' . $this->getAuthor()->getId(); } else { $constraint = '{{table}}.author_id=0'; } $collection->joinField('position', 'sample_news_author_product', 'position', 'product_id = entity_id', $constraint, 'left'); $this->setCollection($collection); parent::_prepareCollection(); return $this; }
/** * @return string */ protected function _toHtml() { $categoryId = $this->getRequest()->getParam('cid'); $storeId = $this->_getStoreId(); /** @var $rssModel \Magento\Rss\Model\Rss */ $rssModel = $this->_rssFactory->create(); if ($categoryId) { $category = $this->_categoryFactory->create(); $category->load($categoryId); if ($category && $category->getId()) { /** @var $layer \Magento\Catalog\Model\Layer */ $layer = $this->_catalogLayer->setStore($storeId); //want to load all products no matter anchor or not $category->setIsAnchor(true); $newUrl = $category->getUrl(); $title = $category->getName(); $rssModel->_addHeader(array('title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8')); $_collection = $category->getCollection(); $_collection->addAttributeToSelect('url_key')->addAttributeToSelect('name')->addAttributeToSelect('is_anchor')->addAttributeToFilter('is_active', 1)->addIdFilter($category->getChildren())->load(); /** @var $productCollection \Magento\Catalog\Model\Resource\Product\Collection */ $productCollection = $this->_collectionFactory->create(); $currentCategory = $layer->setCurrentCategory($category); $layer->prepareProductCollection($productCollection); $productCollection->addCountToCategories($_collection); $category->getProductCollection()->setStoreId($storeId); /* only load latest 50 products */ $_productCollection = $currentCategory->getProductCollection()->addAttributeToSort('updated_at', 'desc')->setVisibility($this->_visibility->getVisibleInCatalogIds())->setCurPage(1)->setPageSize(50); if ($_productCollection->getSize() > 0) { $args = array('rssObj' => $rssModel); foreach ($_productCollection as $_product) { $args['product'] = $_product; $this->addNewItemXmlCallback($args); } } } } return $rssModel->createRssXml(); }
/** * Prepare products collection, defined collection filters (category, product type) * * @return Extended */ protected function _prepareCollection() { /* @var $collection \Magento\Catalog\Model\Resource\Product\Collection */ $collection = $this->_collectionFactory->create()->setStoreId(0)->addAttributeToSelect('name'); if ($categoryId = $this->getCategoryId()) { $category = $this->_categoryFactory->create()->load($categoryId); if ($category->getId()) { // $collection->addCategoryFilter($category); $productIds = $category->getProductsPosition(); $productIds = array_keys($productIds); if (empty($productIds)) { $productIds = 0; } $collection->addFieldToFilter('entity_id', ['in' => $productIds]); } } if ($productTypeId = $this->getProductTypeId()) { $collection->addAttributeToFilter('type_id', $productTypeId); } $this->setCollection($collection); return parent::_prepareCollection(); }
/** * Generate url rewrites for products assigned to category * * @param Category $category * @return array */ protected function generateProductUrlRewrites(Category $category) { $this->isSkippedProduct = []; $saveRewriteHistory = $category->getData('save_rewrites_history'); $storeId = $category->getStoreId(); $productUrls = []; if ($category->getAffectedProductIds()) { $this->isSkippedProduct = $category->getAffectedProductIds(); $collection = $this->productCollectionFactory->create()->setStoreId($storeId)->addIdFilter($category->getAffectedProductIds())->addAttributeToSelect('name')->addAttributeToSelect('url_key')->addAttributeToSelect('url_path'); foreach ($collection as $product) { $product->setStoreId($storeId); $product->setData('save_rewrites_history', $saveRewriteHistory); $productUrls = array_merge($productUrls, $this->productUrlRewriteGenerator->generate($product)); } } else { $productUrls = array_merge($productUrls, $this->getCategoryProductsUrlRewrites($category, $storeId, $saveRewriteHistory)); } foreach ($this->childrenCategoriesProvider->getChildren($category, true) as $childCategory) { $productUrls = array_merge($productUrls, $this->getCategoryProductsUrlRewrites($childCategory, $storeId, $saveRewriteHistory)); } return $productUrls; }
/** * Get category products collection * * @return \Magento\Framework\Data\Collection\AbstractDb */ public function getProductCollection() { $collection = $this->_productCollectionFactory->create()->setStoreId($this->getStoreId())->addCategoryFilter($this); return $collection; }
/** * @param \Magento\Catalog\Model\Category $category * @return \Magento\Catalog\Model\Resource\Product\Collection */ public function getCollection(\Magento\Catalog\Model\Category $category) { return $this->collectionFactory->create(); }
/** * Get random items collection with or without related children * * @param int $limit * @param bool $nonChildrenOnly * @return ImportCollection */ protected function _getItemsRandomCollection($limit, $nonChildrenOnly = false) { $collection = $this->_orderItemCollectionFactory->create()->setOrderFilter($this)->setRandomOrder(); if ($nonChildrenOnly) { $collection->filterByParent(); } $products = []; foreach ($collection as $item) { $products[] = $item->getProductId(); } $productsCollection = $this->productListFactory->create()->addIdFilter($products)->setVisibility($this->_productVisibility->getVisibleInSiteIds())->addPriceData()->setPageSize($limit)->load(); foreach ($collection as $item) { $product = $productsCollection->getItemById($item->getProductId()); if ($product) { $item->setProduct($product); } } return $collection; }
/** * Form XML for international shipment request * As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName /> must be * after <FromFirstName /> * * @param \Magento\Framework\Object $request * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _formIntlShipmentRequest(\Magento\Framework\Object $request) { $packageParams = $request->getPackageParams(); $height = $packageParams->getHeight(); $width = $packageParams->getWidth(); $length = $packageParams->getLength(); $girth = $packageParams->getGirth(); $packageWeight = $request->getPackageWeight(); if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) { $packageWeight = $this->_carrierHelper->convertMeasureWeight($request->getPackageWeight(), $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND); } if ($packageParams->getDimensionUnits() != \Zend_Measure_Length::INCH) { $length = round($this->_carrierHelper->convertMeasureDimension($packageParams->getLength(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); $width = round($this->_carrierHelper->convertMeasureDimension($packageParams->getWidth(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); $height = round($this->_carrierHelper->convertMeasureDimension($packageParams->getHeight(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); } if ($packageParams->getGirthDimensionUnits() != \Zend_Measure_Length::INCH) { $girth = round($this->_carrierHelper->convertMeasureDimension($packageParams->getGirth(), $packageParams->getGirthDimensionUnits(), \Zend_Measure_Length::INCH)); } $container = $request->getPackagingType(); switch ($container) { case 'VARIABLE': $container = 'VARIABLE'; break; case 'FLAT RATE ENVELOPE': $container = 'FLATRATEENV'; break; case 'FLAT RATE BOX': $container = 'FLATRATEBOX'; break; case 'RECTANGULAR': $container = 'RECTANGULAR'; break; case 'NONRECTANGULAR': $container = 'NONRECTANGULAR'; break; default: $container = 'VARIABLE'; } $shippingMethod = $request->getShippingMethod(); list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode()); // the wrap node needs for remove xml declaration above $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']); $method = ''; $service = $this->getCode('service_to_code', $shippingMethod); if ($service == 'Priority') { $method = 'Priority'; $rootNode = 'PriorityMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } else { if ($service == 'First Class') { $method = 'FirstClass'; $rootNode = 'FirstClassMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } else { $method = 'Express'; $rootNode = 'ExpressMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } } $xml->addAttribute('USERID', $this->getConfigData('userid')); $xml->addAttribute('PASSWORD', $this->getConfigData('password')); $xml->addChild('Option'); $xml->addChild('Revision', self::DEFAULT_REVISION); $xml->addChild('ImageParameters'); $xml->addChild('FromFirstName', $request->getShipperContactPersonFirstName()); $xml->addChild('FromLastName', $request->getShipperContactPersonLastName()); $xml->addChild('FromFirm', $request->getShipperContactCompanyName()); $xml->addChild('FromAddress1', $request->getShipperAddressStreet2()); $xml->addChild('FromAddress2', $request->getShipperAddressStreet1()); $xml->addChild('FromCity', $request->getShipperAddressCity()); $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode()); $xml->addChild('FromZip5', $fromZip5); $xml->addChild('FromZip4', $fromZip4); $xml->addChild('FromPhone', $request->getShipperContactPhoneNumber()); if ($method != 'FirstClass') { if ($request->getReferenceData()) { $referenceData = $request->getReferenceData() . ' P' . $request->getPackageId(); } else { $referenceData = $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId(); } $xml->addChild('FromCustomsReference', 'Order #' . $referenceData); } $xml->addChild('ToFirstName', $request->getRecipientContactPersonFirstName()); $xml->addChild('ToLastName', $request->getRecipientContactPersonLastName()); $xml->addChild('ToFirm', $request->getRecipientContactCompanyName()); $xml->addChild('ToAddress1', $request->getRecipientAddressStreet1()); $xml->addChild('ToAddress2', $request->getRecipientAddressStreet2()); $xml->addChild('ToCity', $request->getRecipientAddressCity()); $xml->addChild('ToProvince', $request->getRecipientAddressStateOrProvinceCode()); $xml->addChild('ToCountry', $this->_getCountryName($request->getRecipientAddressCountryCode())); $xml->addChild('ToPostalCode', $request->getRecipientAddressPostalCode()); $xml->addChild('ToPOBoxFlag', 'N'); $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber()); $xml->addChild('ToFax'); $xml->addChild('ToEmail'); if ($method != 'FirstClass') { $xml->addChild('NonDeliveryOption', 'Return'); } if ($method == 'FirstClass') { if (stripos($shippingMethod, 'Letter') !== false) { $xml->addChild('FirstClassMailType', 'LETTER'); } else { if (stripos($shippingMethod, 'Flat') !== false) { $xml->addChild('FirstClassMailType', 'FLAT'); } else { $xml->addChild('FirstClassMailType', 'PARCEL'); } } } if ($method != 'FirstClass') { $xml->addChild('Container', $container); } $shippingContents = $xml->addChild('ShippingContents'); $packageItems = $request->getPackageItems(); // get countries of manufacture $countriesOfManufacture = []; $productIds = []; foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\Object(); $item->setData($itemShipment); $productIds[] = $item->getProductId(); } $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture'); foreach ($productCollection as $product) { $countriesOfManufacture[$product->getId()] = $product->getCountryOfManufacture(); } $packagePoundsWeight = $packageOuncesWeight = 0; // for ItemDetail foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\Object(); $item->setData($itemShipment); $itemWeight = $item->getWeight() * $item->getQty(); if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) { $itemWeight = $this->_carrierHelper->convertMeasureWeight($itemWeight, $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND); } if (!empty($countriesOfManufacture[$item->getProductId()])) { $countryOfManufacture = $this->_getCountryName($countriesOfManufacture[$item->getProductId()]); } else { $countryOfManufacture = ''; } $itemDetail = $shippingContents->addChild('ItemDetail'); $itemDetail->addChild('Description', $item->getName()); $ceiledQty = ceil($item->getQty()); if ($ceiledQty < 1) { $ceiledQty = 1; } $individualItemWeight = $itemWeight / $ceiledQty; $itemDetail->addChild('Quantity', $ceiledQty); $itemDetail->addChild('Value', $item->getCustomsValue() * $item->getQty()); list($individualPoundsWeight, $individualOuncesWeight) = $this->_convertPoundOunces($individualItemWeight); $itemDetail->addChild('NetPounds', $individualPoundsWeight); $itemDetail->addChild('NetOunces', $individualOuncesWeight); $itemDetail->addChild('HSTariffNumber', 0); $itemDetail->addChild('CountryOfOrigin', $countryOfManufacture); list($itemPoundsWeight, $itemOuncesWeight) = $this->_convertPoundOunces($itemWeight); $packagePoundsWeight += $itemPoundsWeight; $packageOuncesWeight += $itemOuncesWeight; } $additionalPackagePoundsWeight = floor($packageOuncesWeight / self::OUNCES_POUND); $packagePoundsWeight += $additionalPackagePoundsWeight; $packageOuncesWeight -= $additionalPackagePoundsWeight * self::OUNCES_POUND; if ($packagePoundsWeight + $packageOuncesWeight / self::OUNCES_POUND < $packageWeight) { list($packagePoundsWeight, $packageOuncesWeight) = $this->_convertPoundOunces($packageWeight); } $xml->addChild('GrossPounds', $packagePoundsWeight); $xml->addChild('GrossOunces', $packageOuncesWeight); if ($packageParams->getContentType() == 'OTHER' && $packageParams->getContentTypeOther() != null) { $xml->addChild('ContentType', $packageParams->getContentType()); $xml->addChild('ContentTypeOther ', $packageParams->getContentTypeOther()); } else { $xml->addChild('ContentType', $packageParams->getContentType()); } $xml->addChild('Agreement', 'y'); $xml->addChild('ImageType', 'PDF'); $xml->addChild('ImageLayout', 'ALLINONEFILE'); if ($method == 'FirstClass') { $xml->addChild('Container', $container); } // set size if ($packageParams->getSize()) { $xml->addChild('Size', $packageParams->getSize()); } // set dimensions $xml->addChild('Length', $length); $xml->addChild('Width', $width); $xml->addChild('Height', $height); if ($girth) { $xml->addChild('Girth', $girth); } $xml = $xmlWrap->{$rootNode}->asXML(); return $xml; }
/** * Form array with appropriate structure for shipment request * * @param \Magento\Framework\Object $request * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _formShipmentRequest(\Magento\Framework\Object $request) { if ($request->getReferenceData()) { $referenceData = $request->getReferenceData() . $request->getPackageId(); } else { $referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId(); } $packageParams = $request->getPackageParams(); $customsValue = $packageParams->getCustomsValue(); $height = $packageParams->getHeight(); $width = $packageParams->getWidth(); $length = $packageParams->getLength(); $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LB' : 'KG'; $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM'; $unitPrice = 0; $itemsQty = 0; $itemsDesc = []; $countriesOfManufacture = []; $productIds = []; $packageItems = $request->getPackageItems(); foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\Object(); $item->setData($itemShipment); $unitPrice += $item->getPrice(); $itemsQty += $item->getQty(); $itemsDesc[] = $item->getName(); $productIds[] = $item->getProductId(); } // get countries of manufacture $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture'); foreach ($productCollection as $product) { $countriesOfManufacture[] = $product->getCountryOfManufacture(); } $paymentType = $request->getIsReturn() ? 'RECIPIENT' : 'SENDER'; $requestClient = ['RequestedShipment' => ['ShipTimestamp' => time(), 'DropoffType' => $this->getConfigData('dropoff'), 'PackagingType' => $request->getPackagingType(), 'ServiceType' => $request->getShippingMethod(), 'Shipper' => ['Contact' => ['PersonName' => $request->getShipperContactPersonName(), 'CompanyName' => $request->getShipperContactCompanyName(), 'PhoneNumber' => $request->getShipperContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getShipperAddressStreet()], 'City' => $request->getShipperAddressCity(), 'StateOrProvinceCode' => $request->getShipperAddressStateOrProvinceCode(), 'PostalCode' => $request->getShipperAddressPostalCode(), 'CountryCode' => $request->getShipperAddressCountryCode()]], 'Recipient' => ['Contact' => ['PersonName' => $request->getRecipientContactPersonName(), 'CompanyName' => $request->getRecipientContactCompanyName(), 'PhoneNumber' => $request->getRecipientContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getRecipientAddressStreet()], 'City' => $request->getRecipientAddressCity(), 'StateOrProvinceCode' => $request->getRecipientAddressStateOrProvinceCode(), 'PostalCode' => $request->getRecipientAddressPostalCode(), 'CountryCode' => $request->getRecipientAddressCountryCode(), 'Residential' => (bool) $this->getConfigData('residence_delivery')]], 'ShippingChargesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'LabelSpecification' => ['LabelFormatType' => 'COMMON2D', 'ImageType' => 'PNG', 'LabelStockType' => 'PAPER_8.5X11_TOP_HALF_LABEL'], 'RateRequestTypes' => ['ACCOUNT'], 'PackageCount' => 1, 'RequestedPackageLineItems' => ['SequenceNumber' => '1', 'Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'CustomerReferences' => ['CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => $referenceData], 'SpecialServicesRequested' => ['SpecialServiceTypes' => 'SIGNATURE_OPTION', 'SignatureOptionDetail' => ['OptionType' => $packageParams->getDeliveryConfirmation()]]]]]; // for international shipping if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) { $requestClient['RequestedShipment']['CustomsClearanceDetail'] = ['CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue], 'DutiesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'Commodities' => ['Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'NumberOfPieces' => 1, 'CountryOfManufacture' => implode(',', array_unique($countriesOfManufacture)), 'Description' => implode(', ', $itemsDesc), 'Quantity' => ceil($itemsQty), 'QuantityUnits' => 'pcs', 'UnitPrice' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $unitPrice], 'CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue]]]; } if ($request->getMasterTrackingId()) { $requestClient['RequestedShipment']['MasterTrackingId'] = $request->getMasterTrackingId(); } // set dimensions if ($length || $width || $height) { $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'] = []; $dimenssions =& $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions']; $dimenssions['Length'] = $length; $dimenssions['Width'] = $width; $dimenssions['Height'] = $height; $dimenssions['Units'] = $dimensionsUnits; } return $this->_getAuthDetails() + $requestClient; }
/** * Retrieve advanced search product collection * * @return Collection */ public function getProductCollection() { if ($this->_productCollection === null) { $collection = $this->productCollectionFactory->create(); $this->prepareProductCollection($collection); if (!$collection) { return $collection; } $this->_productCollection = $collection; } return $this->_productCollection; }
/** * Get array of product ids which are matched by rule * * @return array */ public function getMatchingProductIds() { if (is_null($this->_productIds)) { $this->_productIds = array(); $this->setCollectedAttributes(array()); if ($this->getWebsiteIds()) { /** @var $productCollection \Magento\Catalog\Model\Resource\Product\Collection */ $productCollection = $this->_productCollectionFactory->create(); $productCollection->addWebsiteFilter($this->getWebsiteIds()); if ($this->_productsFilter) { $productCollection->addIdFilter($this->_productsFilter); } $this->getConditions()->collectValidatedAttributes($productCollection); $this->_resourceIterator->walk($productCollection->getSelect(), array(array($this, 'callbackValidateProduct')), array('attributes' => $this->getCollectedAttributes(), 'product' => $this->_productFactory->create())); } } return $this->_productIds; }
/** * @return Collection */ protected function _getProductCollection() { if ($this->_productCollection === null) { /** @var Collection $collection */ $collection = $this->_productCollectionFactory->create(); $this->_catalogLayer->prepareProductCollection($collection); $collection->addAttributeToFilter('promotion', 1)->addStoreFilter(); $this->_productCollection = $collection; } return $this->_productCollection; }