/** * Get or create new instance of product * * @return \Magento\Catalog\Model\Product */ private function _getProduct() { if (!$this->hasData('product')) { $this->setProduct($this->_productFactory->create()); } return $this->getProduct(); }
/** * Product variations attributes validation * * @param Product $parentProduct * @param array $products * @param RequestInterface $request * @return array */ protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request) { $this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]); $validationResult = []; foreach ($products as $productData) { $product = $this->productFactory->create(); $product->setData('_edit_mode', true); $storeId = $request->getParam('store'); if ($storeId) { $product->setStoreId($storeId); } $product->setAttributeSetId($parentProduct->getAttributeSetId()); $product->addData($this->getRequiredDataFromProduct($parentProduct)); $product->addData($productData); $product->setCollectExceptionMessages(true); $configurableAttribute = []; $encodedData = $productData['configurable_attribute']; if ($encodedData) { $configurableAttribute = $this->jsonHelper->jsonDecode($encodedData); } $configurableAttribute = implode('-', $configurableAttribute); $errorAttributes = $product->validate(); if (is_array($errorAttributes)) { foreach ($errorAttributes as $attributeCode => $result) { if (is_string($result)) { $key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode; $validationResult[$key] = $result; } } } } return $validationResult; }
/** * @return string */ protected function _toHtml() { $storeId = $this->_getStoreId(); $storeModel = $this->_storeManager->getStore($storeId); $newUrl = $this->_urlBuilder->getUrl('rss/catalog/new/store_id/' . $storeId); $title = __('New Products from %1', $storeModel->getFrontendName()); $lang = $this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeModel); /** @var $rssObj \Magento\Rss\Model\Rss */ $rssObj = $this->_rssFactory->create(); $rssObj->_addHeader(array('title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8', 'language' => $lang)); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->_productFactory->create(); $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 $products \Magento\Catalog\Model\Resource\Product\Collection */ $products = $product->getCollection(); $products->setStoreId($storeId); $products->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')->addAttributeToSelect(array('name', 'short_description', 'description'), 'inner')->addAttributeToSelect(array('price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_enabled', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'), 'left')->applyFrontendPriceLimitations(); $products->setVisibility($this->_visibility->getVisibleInCatalogIds()); /* using resource iterator to load the data one by one instead of loading all at the same time. loading all data at the same time can cause the big memory allocation. */ $this->_resourceIterator->walk($products->getSelect(), array(array($this, 'addNewItemXmlCallback')), array('rssObj' => $rssObj, 'product' => $product)); return $rssObj->createRssXml(); }
/** * Populate product with variation of attributes * * @param \Magento\Catalog\Api\Data\ProductInterface $product * @param array $attributes * @return \Magento\Catalog\Api\Data\ProductInterface[] */ public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes) { $variations = $this->variationMatrix->getVariations($attributes); $products = []; foreach ($variations as $variation) { $price = $product->getPrice(); /** @var \Magento\Catalog\Model\Product $item */ $item = $this->productFactory->create(); $item->setData($product->getData()); $suffix = ''; foreach ($variation as $attributeId => $valueInfo) { $suffix .= '-' . $valueInfo['value']; $customAttribute = $this->customAttributeFactory->create()->setAttributeCode($attributes[$attributeId]['attribute_code'])->setValue($valueInfo['value']); $customAttributes = array_merge($item->getCustomAttributes(), [$attributes[$attributeId]['attribute_code'] => $customAttribute]); $item->setData('custom_attributes', $customAttributes); $priceInfo = $valueInfo['price']; $price += (!empty($priceInfo['is_percent']) ? $product->getPrice() / 100.0 : 1.0) * $priceInfo['pricing_value']; } $item->setPrice($price); $item->setName($product->getName() . $suffix); $item->setSku($product->getSku() . $suffix); $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE); $products[] = $item; } return $products; }
/** * Create product duplicate * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product */ public function copy(\Magento\Catalog\Model\Product $product) { $product->getWebsiteIds(); $product->getCategoryIds(); $duplicate = $this->productFactory->create(); $duplicate->setData($product->getData()); $duplicate->setIsDuplicate(true); $duplicate->setOriginalId($product->getId()); $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED); $duplicate->setCreatedAt(null); $duplicate->setUpdatedAt(null); $duplicate->setId(null); $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID); $this->copyConstructor->build($product, $duplicate); $isDuplicateSaved = false; do { $urlKey = $duplicate->getUrlKey(); $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1'; $duplicate->setUrlKey($urlKey); try { $duplicate->save(); $isDuplicateSaved = true; } catch (DuplicateEntryException $e) { } } while (!$isDuplicateSaved); $product->getOptionInstance()->duplicate($product->getId(), $duplicate->getId()); $product->getResource()->duplicate($product->getId(), $duplicate->getId()); return $duplicate; }
/** * Products collection. * * @return array */ public function getLoadedProductCollection() { $productsToDisplay = []; $mode = $this->getRequest()->getActionName(); $customerId = $this->getRequest()->getParam('customer_id'); $limit = $this->recommnededHelper->getDisplayLimitByMode($mode); //login customer to receive the recent products $session = $this->sessionFactory->create(); $isLoggedIn = $session->loginById($customerId); $collection = $this->viewed; $productItems = $collection->getItemsCollection()->setPageSize($limit); //get the product ids from items collection $productIds = $productItems->getColumnValues('product_id'); //get product collection to check for salable $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id', ['in' => $productIds]); //show products only if is salable foreach ($productCollection as $product) { if ($product->isSalable()) { $productsToDisplay[$product->getId()] = $product; } } $this->helper->log('Recentlyviewed customer : ' . $customerId . ', mode ' . $mode . ', limit : ' . $limit . ', items found : ' . count($productItems) . ', is customer logged in : ' . $isLoggedIn . ', products :' . count($productsToDisplay)); $session->logout(); return $productsToDisplay; }
/** * Get associated grouped products grid popup * * @return void */ public function execute() { $productId = (int) $this->getRequest()->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->factory->create(); $product->setStoreId($this->getRequest()->getParam('store', 0)); $typeId = $this->getRequest()->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->logException($e); } } $setId = (int) $this->getRequest()->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('current_product', $product); $this->_view->loadLayout(false); $this->_view->renderLayout(); }
/** * Get categories tree as recursive array * * @param int $parentId * @param bool $asJson * @param int $recursionLevel * @return array */ public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3) { $productId = $this->_request->getParam('product'); if ($productId) { $product = $this->_productFactory->create()->setId($productId); $this->_allowedCategoryIds = $product->getCategoryIds(); unset($product); } $result = []; if ($parentId) { try { $category = $this->categoryRepository->get($parentId); } catch (NoSuchEntityException $e) { $category = null; } if ($category) { $tree = $this->_getNodesArray($this->getNode($category, $recursionLevel)); if (!empty($tree) && !empty($tree['children'])) { $result = $tree['children']; } } } else { $result = $this->_getNodesArray($this->getRoot(null, $recursionLevel)); } if ($asJson) { return $this->_jsonEncoder->encode($result); } $this->_allowedCategoryIds = []; return $result; }
/** * Create product duplicate * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product */ public function copy(\Magento\Catalog\Model\Product $product) { $product->getWebsiteIds(); $product->getCategoryIds(); /** @var \Magento\Catalog\Model\Product $duplicate */ $duplicate = $this->productFactory->create(); $duplicate->setData($product->getData()); $duplicate->setOptions([]); $duplicate->setIsDuplicate(true); $duplicate->setOriginalId($product->getEntityId()); $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED); $duplicate->setCreatedAt(null); $duplicate->setUpdatedAt(null); $duplicate->setId(null); $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID); $this->copyConstructor->build($product, $duplicate); $isDuplicateSaved = false; do { $urlKey = $duplicate->getUrlKey(); $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1'; $duplicate->setUrlKey($urlKey); try { $duplicate->save(); $isDuplicateSaved = true; } catch (\Magento\Framework\Exception\AlreadyExistsException $e) { } } while (!$isDuplicateSaved); $this->getOptionRepository()->duplicate($product, $duplicate); $metadata = $this->getMetadataPool()->getMetadata(ProductInterface::class); $product->getResource()->duplicate($product->getData($metadata->getLinkField()), $duplicate->getData($metadata->getLinkField())); return $duplicate; }
/** * Get associated grouped products grid popup * * @return \Magento\Framework\View\Result\Layout */ public function execute() { $productId = (int) $this->getRequest()->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->factory->create(); $product->setStoreId($this->getRequest()->getParam('store', 0)); $typeId = $this->getRequest()->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->critical($e); } } $setId = (int) $this->getRequest()->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('current_product', $product); /** @var \Magento\Framework\View\Result\Layout $resultLayout */ $resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT); return $resultLayout; }
protected function setUp() { $this->productBuilder = $this->getMock('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Builder', ['build'], [], '', false); $this->product = $this->getMockBuilder('Magento\\Catalog\\Model\\Product')->disableOriginalConstructor()->setMethods(['addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep', '__wakeup', 'getAttributes', 'setAttributeSetId'])->getMock(); $this->product->expects($this->any())->method('getTypeId')->will($this->returnValue('simple')); $this->product->expects($this->any())->method('getStoreId')->will($this->returnValue('1')); $this->product->expects($this->any())->method('getAttributes')->will($this->returnValue([])); $this->productBuilder->expects($this->any())->method('build')->will($this->returnValue($this->product)); $this->resultPage = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\Page')->disableOriginalConstructor()->getMock(); $resultPageFactory = $this->getMockBuilder('Magento\\Framework\\View\\Result\\PageFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $resultPageFactory->expects($this->any())->method('create')->willReturn($this->resultPage); $this->resultForward = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\Forward')->disableOriginalConstructor()->getMock(); $resultForwardFactory = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\ForwardFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $resultForwardFactory->expects($this->any())->method('create')->willReturn($this->resultForward); $this->resultPage->expects($this->any())->method('getLayout')->willReturn($this->layout); $this->resultRedirectFactory = $this->getMock('Magento\\Backend\\Model\\View\\Result\\RedirectFactory', ['create'], [], '', false); $this->resultRedirect = $this->getMock('Magento\\Backend\\Model\\View\\Result\\Redirect', [], [], '', false); $this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect); $this->initializationHelper = $this->getMock('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Initialization\\Helper', [], [], '', false); $this->productFactory = $this->getMockBuilder('Magento\\Catalog\\Model\\ProductFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); $this->resultJson = $this->getMock('Magento\\Framework\\Controller\\Result\\Json', [], [], '', false); $this->resultJsonFactory = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\JsonFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->resultJsonFactory->expects($this->any())->method('create')->willReturn($this->resultJson); $additionalParams = ['resultRedirectFactory' => $this->resultRedirectFactory]; $this->action = (new ObjectManagerHelper($this))->getObject('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Validate', ['context' => $this->initContext($additionalParams), 'productBuilder' => $this->productBuilder, 'resultPageFactory' => $resultPageFactory, 'resultForwardFactory' => $resultForwardFactory, 'initializationHelper' => $this->initializationHelper, 'resultJsonFactory' => $this->resultJsonFactory, 'productFactory' => $this->productFactory]); }
/** * Build product based on user request * * @param RequestInterface $request * @return \Magento\Catalog\Model\Product */ public function build(RequestInterface $request) { $productId = (int) $request->getParam('id'); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $product->setStoreId($request->getParam('store', 0)); $typeId = $request->getParam('type'); if (!$productId && $typeId) { $product->setTypeId($typeId); } $product->setData('_edit_mode', true); if ($productId) { try { $product->load($productId); } catch (\Exception $e) { $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); $this->logger->critical($e); } } $setId = (int) $request->getParam('set'); if ($setId) { $product->setAttributeSetId($setId); } $this->registry->register('product', $product); $this->registry->register('current_product', $product); $this->wysiwygConfig->setStoreId($request->getParam('store')); return $product; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing product links:'); $entityFileAssociation = ['related', 'upsell', 'crosssell']; foreach ($this->postInstaller->getInstalledModuleList() as $moduleName) { foreach ($entityFileAssociation as $linkType) { $fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/Links/' . $linkType . '.csv'; $fileName = $this->fixtureHelper->getPath($fileName); if (!$fileName) { continue; } /** @var \Magento\SampleData\Helper\Csv\ReaderFactory $csvReader */ $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); foreach ($csvReader as $row) { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productFactory->create(); $productId = $product->getIdBySku($row['sku']); if (!$productId) { continue; } $product->setId($productId); $links = [$linkType => []]; foreach (explode("\n", $row['linked_sku']) as $linkedProductSku) { $linkedProductId = $product->getIdBySku($linkedProductSku); if ($linkedProductId) { $links[$linkType][$linkedProductId] = []; } } $this->linksInitializer->initializeLinks($product, $links); $product->getLinkInstance()->saveProductRelations($product); $this->logger->logInline('.'); } } } }
/** * @return array */ public function getMediaAttributes() { static $simple; if (empty($simple)) { $simple = $this->productFactory->create()->setTypeId(Type::TYPE_SIMPLE)->getMediaAttributes(); } return $simple; }
/** * @param int $storeId * @param int $customerGroupId * @return \Magento\Catalog\Model\ResourceModel\Product\Collection */ public function getProductsCollection($storeId, $customerGroupId) { $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId(); /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $product->setStoreId($storeId); $collection = $product->getResourceCollection()->addPriceDataFieldFilter('%s < %s', ['final_price', 'price'])->addPriceData($customerGroupId, $websiteId)->addAttributeToSelect(['name', 'short_description', 'description', 'price', 'thumbnail', 'special_price', 'special_to_date', 'msrp_display_actual_price_type', 'msrp'], 'left')->addAttributeToSort('name', 'asc'); return $collection; }
/** * Get product id * * @param \Magento\Sales\Model\Order\Admin\Item $subject * @param callable $proceed * @param \Magento\Sales\Model\Order\Item $item * * @return int * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundGetProductId(\Magento\Sales\Model\Order\Admin\Item $subject, \Closure $proceed, \Magento\Sales\Model\Order\Item $item) { if ($item->getProductType() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) { $productOptions = $item->getProductOptions(); $product = $this->productFactory->create(); return $product->getIdBySku($productOptions['simple_sku']); } return $proceed($item); }
/** * Get the products to display for table. * * @return $this */ public function getLoadedProductCollection() { $mode = $this->getRequest()->getActionName(); $limit = $this->recommnededHelper->getDisplayLimitByMode($mode); $productIds = $this->recommnededHelper->getProductPushIds(); $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', ['in' => $productIds]); $productCollection->getSelect()->limit($limit); //important check the salable product in template return $productCollection; }
/** * Apply sorting and filtering to collection * * @return $this */ protected function _prepareCollection() { $collection = $this->_productFactory->create()->getCollection()->setOrder('id')->addAttributeToSelect('name')->addAttributeToSelect('sku')->addAttributeToSelect('price')->addAttributeToSelect('attribute_set_id')->addAttributeToFilter('entity_id', ['nin' => $this->_getSelectedProducts()])->addAttributeToFilter('type_id', ['in' => $this->getAllowedSelectionTypes()])->addFilterByRequiredOptions()->addStoreFilter(\Magento\Store\Model\Store::DEFAULT_STORE_ID); if ($this->getFirstShow()) { $collection->addIdFilter('-1'); $this->setEmptyText(__('Please enter search conditions to view products.')); } $this->setCollection($collection); return parent::_prepareCollection(); }
protected function setUp() { $this->product = $this->getMock('Magento\\Catalog\\Model\\Product', [], [], '', false); $this->productFactory = $this->getMock('Magento\\Catalog\\Model\\ProductFactory', ['create'], [], '', false); $this->productFactory->expects($this->any())->method('create')->will($this->returnValue($this->product)); $this->visibility = $this->getMock('Magento\\Catalog\\Model\\Product\\Visibility', [], [], '', false); $this->timezone = $this->getMock('Magento\\Framework\\Stdlib\\DateTime\\Timezone', [], [], '', false); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->newProducts = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Rss\\Product\\NewProducts', ['productFactory' => $this->productFactory, 'visibility' => $this->visibility, 'localeDate' => $this->timezone]); }
public function testExecuteNullProduct() { $this->productMock->expects($this->once())->method('load')->with(59)->willReturn($this->productMock); $this->productModelFactoryMock->expects($this->once())->method('create')->willReturn($this->productMock); $this->swatchHelperMock->expects($this->once())->method('getAttributesFromConfigurable')->with($this->productMock)->willReturn([$this->attributeMock]); $this->swatchHelperMock->expects($this->once())->method('loadVariationByFallback')->with($this->productMock, ['size' => 454])->willReturn(null); $this->swatchHelperMock->expects($this->once())->method('getProductMediaGallery')->with($this->productMock)->willReturn($this->mediaGallery); $this->jsonMock->expects($this->once())->method('setData')->with($this->mediaGallery)->will($this->returnSelf()); $result = $this->controller->execute(); $this->assertInstanceOf('\\Magento\\Framework\\Controller\\Result\\Json', $result); }
/** * Load product by SKU * * @param string $productSku * @return \Magento\Catalog\Model\Product * @throws NoSuchEntityException */ public function load($productSku) { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productFactory->create(); $productId = $product->getIdBySku($productSku); if (!$productId) { throw new NoSuchEntityException('There is no product with provided SKU'); } $product->load($productId); return $product; }
/** * Validate Product Rule Condition * * @param \Magento\Framework\Object $object * @return bool */ public function validate(\Magento\Framework\Object $object) { //@todo reimplement this method when is fixed MAGETWO-5713 /** @var \Magento\Catalog\Model\Product $product */ $product = $object->getProduct(); if (!$product instanceof \Magento\Catalog\Model\Product) { $product = $this->_productFactory->create()->load($object->getProductId()); } $product->setQuoteItemQty($object->getQty())->setQuoteItemPrice($object->getPrice())->setQuoteItemRowTotal($object->getBaseRowTotal()); return parent::validate($product); }
/** * @return void */ protected function _construct() { $this->_blockGroup = 'Magento_Reports'; $this->_controller = 'adminhtml_review_detail'; $product = $this->_productFactory->create()->load($this->getRequest()->getParam('id')); $this->_headerText = __('Reviews for %1', $product->getName()); parent::_construct(); $this->buttonList->remove('add'); $this->setBackUrl($this->getUrl('reports/report_review/product/')); $this->_addBackButton(); }
/** * @return array */ public function getOldSkus() { if (!$this->oldSkus) { $columns = ['entity_id', 'type_id', 'attribute_set_id', 'sku']; foreach ($this->productFactory->create()->getProductEntitiesInfo($columns) as $info) { $typeId = $info['type_id']; $sku = $info['sku']; $this->oldSkus[$sku] = ['type_id' => $typeId, 'attr_set_id' => $info['attribute_set_id'], 'entity_id' => $info['entity_id'], 'supported_type' => isset($this->productTypeModels[$typeId])]; } } return $this->oldSkus; }
/** * Generate url rewrites for products assigned to website * * @param int $websiteId * @param int $originWebsiteId * @return array */ protected function generateProductUrls($websiteId, $originWebsiteId) { $urls = []; $websiteIds = $websiteId != $originWebsiteId ? [$websiteId, $originWebsiteId] : [$websiteId]; $collection = $this->productFactory->create()->getCollection()->addCategoryIds()->addAttributeToSelect(['name', 'url_path', 'url_key'])->addWebsiteFilter($websiteIds); foreach ($collection as $product) { /** @var \Magento\Catalog\Model\Product $product */ $product->setStoreId(Store::DEFAULT_STORE_ID); $urls = array_merge($urls, $this->productUrlRewriteGenerator->generate($product)); } return $urls; }
/** * @param int $storeId * @return \Magento\Catalog\Model\ResourceModel\Product\Collection */ public function getProductsCollection($storeId) { /** @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); $todayStartOfDayDate = $this->localeDate->date()->setTime(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 $products \Magento\Catalog\Model\ResourceModel\Product\Collection */ $products = $product->getResourceCollection(); $products->setStoreId($storeId); $products->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')->addAttributeToSelect(['name', 'short_description', 'description'], 'inner')->addAttributeToSelect(['price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'], 'left')->applyFrontendPriceLimitations(); $products->setVisibility($this->visibility->getVisibleInCatalogIds()); return $products; }
/** * @return \Magento\Catalog\Model\ResourceModel\Product\Collection */ public function getProductsCollection() { /* @var $product \Magento\Catalog\Model\Product */ $product = $this->productFactory->create(); /* @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */ $collection = $product->getCollection(); /** @var $resourceStock \Magento\CatalogInventory\Model\ResourceModel\Stock */ $resourceStock = $this->stockFactory->create(); $resourceStock->addLowStockFilter($collection, ['qty', 'notify_stock_qty', 'low_stock_date', 'use_config' => 'use_config_notify_stock_qty']); $collection->addAttributeToSelect('name', true)->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])->setOrder('low_stock_date'); $this->eventManager->dispatch('rss_catalog_notify_stock_collection_select', ['collection' => $collection]); return $collection; }
protected function setUp() { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->mathDivision = $this->getMock('\\Magento\\Framework\\Math\\Division', ['getExactDivision'], [], '', false); $this->localeFormat = $this->getMockForAbstractClass('\\Magento\\Framework\\Locale\\FormatInterface', ['getNumber']); $this->localeFormat->expects($this->any())->method('getNumber')->willReturn($this->qty); $this->object = $this->objectManagerHelper->getObject('Magento\\Framework\\DataObject'); $this->objectFactory = $this->getMock('\\Magento\\Framework\\DataObject\\Factory', ['create'], [], '', false); $this->objectFactory->expects($this->any())->method('create')->willReturn($this->object); $this->product = $this->getMock('Magento\\Catalog\\Model\\Product', ['load', 'isComposite', '__wakeup', 'isSaleable'], [], '', false); $this->productFactory = $this->getMock('Magento\\Catalog\\Model\\ProductFactory', ['create'], [], '', false); $this->productFactory->expects($this->any())->method('create')->willReturn($this->product); $this->stockStateProvider = $this->objectManagerHelper->getObject('Magento\\CatalogInventory\\Model\\StockStateProvider', ['mathDivision' => $this->mathDivision, 'localeFormat' => $this->localeFormat, 'objectFactory' => $this->objectFactory, 'productFactory' => $this->productFactory, 'qtyCheckApplicable' => $this->qtyCheckApplicable]); }
public function execute() { $params = $this->getRequest()->getParams(); /** @var \Magento\Checkout\Model\Cart $cart */ $cart = $this->cartFactory->create(); $successMessage = ''; $websiteId = $this->storeManager->getStore()->getWebsiteId(); foreach ($params as $key => $product) { if ($product && is_array($product)) { $productModel = $this->productFactory->create(); // loadByAttribute() return false if the product was not found. There is no need to check the ID, // but lets stay on the safe side for the future Magento releases /** @var \Magento\Catalog\Model\Product $productBySKU */ $productBySKU = $productModel->loadByAttribute('sku', $product['sku']); if (!$productBySKU || !($productId = $productBySKU->getId())) { continue; } $stockItem = $this->stockItemApiFactory->create(); /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItemResource */ $stockItemResource = $this->stockItemApiResourceFactory->create(); $stockItemResource->loadByProductId($stockItem, $productId, $websiteId); $qty = $stockItem->getQty(); try { if (!$cart->getQuote()->hasProductId($productId) && is_numeric($product['qty']) && $qty > $product['qty']) { $cart->addProduct($productBySKU, (int) $product['qty']); $successMessage .= __('%1 was added to your shopping cart.' . '</br>', $this->escaper->escapeHtml($productBySKU->getName())); } unset($params[$key]); } catch (\Exception $e) { $this->rejoinerHelper->log($e->getMessage()); } } } if (isset($params['coupon_code'])) { $cart->getQuote()->setCouponCode($params['coupon_code'])->collectTotals(); } try { $cart->getQuote()->save(); $cart->save(); } catch (\Exception $e) { $this->rejoinerHelper->log($e->getMessage()); } $this->checkoutSession->setCartWasUpdated(true); if ($successMessage) { $this->messageManager->addSuccess($successMessage); } $url = $this->_url->getUrl('checkout/cart/', ['updateCart' => true]); $this->getResponse()->setRedirect($url); }
/** * @param Product $product * @param \Magento\Catalog\Model\Product $productModel * @return \Magento\Catalog\Model\Product * @throws \RuntimeException */ public function toModel(Product $product, \Magento\Catalog\Model\Product $productModel = null) { /** @var \Magento\Catalog\Model\Product $productModel */ $productModel = $productModel ?: $this->productFactory->create(); $productModel->addData(ExtensibleDataObjectConverter::toFlatArray($product)); if (!is_numeric($productModel->getAttributeSetId())) { $productModel->setAttributeSetId($productModel->getDefaultAttributeSetId()); } if (!$productModel->hasTypeId()) { $productModel->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE); } elseif (!isset($this->productTypes->getTypes()[$productModel->getTypeId()])) { throw new \RuntimeException('Illegal product type'); } return $productModel; }