/** * 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; }
/** * 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; }
public function testGetWebsiteIds() { // set /** @var $model \Magento\Catalog\Model\Product */ $model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product', ['data' => ['website_ids' => [1, 2]]]); $this->assertEquals([1, 2], $model->getWebsiteIds()); // fixture $this->_model->setId(1); $this->assertEquals([1], $this->_model->getWebsiteIds()); }
public function testGetWebsiteIds() { // set /** @var $model \Magento\Catalog\Model\Product */ $model = $this->objectManager->create('Magento\\Catalog\\Model\\Product', ['data' => ['website_ids' => [1, 2]]]); $this->assertEquals([1, 2], $model->getWebsiteIds()); // fixture $this->_model->setId($this->productRepository->get('simple')->getId()); $this->assertEquals([1], $this->_model->getWebsiteIds()); }
private function processCategoriesActions(\Magento\Catalog\Model\Product $product) { $productCategories = $product->getCategoryIds(); $categoriesByWebsite = array(0 => $productCategories); foreach ($product->getWebsiteIds() as $websiteId) { $categoriesByWebsite[$websiteId] = $productCategories; } /** @var \Ess\M2ePro\Model\Listing\Auto\Actions\Mode\Category $autoActionsCategory */ $autoActionsCategory = $this->modelFactory->getObject('Listing\\Auto\\Actions\\Mode\\Category'); $autoActionsCategory->setProduct($product); foreach ($categoriesByWebsite as $websiteId => $categoryIds) { foreach ($categoryIds as $categoryId) { $autoActionsCategory->synchWithAddedCategoryId($categoryId, $websiteId); } } }
/** * 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); $duplicate->save(); $product->getOptionInstance()->duplicate($product->getId(), $duplicate->getId()); $product->getResource()->duplicate($product->getId(), $duplicate->getId()); return $duplicate; }
/** * @param \Magento\Catalog\Model\Product $product */ protected function _printAssignedWebsites(\Magento\Catalog\Model\Product $product) { if (!$this->_printWebsites) { return; } $collection = $this->_websitesFactory->create(); $collection->addIdFilter($product->getWebsiteIds()); $websiteNames = array(); /** @var \Magento\Store\Model\Website $website */ foreach ($collection as $website) { $websiteNames[] = $website->getName(); } echo 'Websites '; echo '[' . implode(',', $websiteNames) . ']'; echo "\t"; }
/** * Save product website relations * * @param \Magento\Catalog\Model\Product $product * @return $this */ protected function _saveWebsiteIds($product) { $websiteIds = $product->getWebsiteIds(); $oldWebsiteIds = []; $product->setIsChangedWebsites(false); $connection = $this->getConnection(); $oldWebsiteIds = $this->getWebsiteIds($product); $insert = array_diff($websiteIds, $oldWebsiteIds); $delete = array_diff($oldWebsiteIds, $websiteIds); if (!empty($insert)) { $data = []; foreach ($insert as $websiteId) { $data[] = ['product_id' => (int) $product->getId(), 'website_id' => (int) $websiteId]; } $connection->insertMultiple($this->getProductWebsiteTable(), $data); } if (!empty($delete)) { foreach ($delete as $websiteId) { $condition = ['product_id = ?' => (int) $product->getId(), 'website_id = ?' => (int) $websiteId]; $connection->delete($this->getProductWebsiteTable(), $condition); } } if (!empty($insert) || !empty($delete)) { $product->setIsChangedWebsites(true); } return $this; }
public function testGetWebsiteIds() { $expected = ['test']; $this->resource->expects($this->once())->method('getWebsiteIds')->will($this->returnValue($expected)); $this->assertEquals($expected, $this->model->getWebsiteIds()); }
/** * Initialize product from data * * @param \Magento\Catalog\Model\Product $product * @param array $productData * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function initializeFromData(\Magento\Catalog\Model\Product $product, array $productData) { unset($productData['custom_attributes']); unset($productData['extension_attributes']); if ($productData) { $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : []; $productData['stock_data'] = $this->stockFilter->filter($stockData); } $productData = $this->normalize($productData); if (!empty($productData['is_downloadable'])) { $productData['product_has_weight'] = 0; } foreach (['category_ids', 'website_ids'] as $field) { if (!isset($productData[$field])) { $productData[$field] = []; } } foreach ($productData['website_ids'] as $websiteId => $checkboxValue) { if (!$checkboxValue) { unset($productData['website_ids'][$websiteId]); } } $wasLockedMedia = false; if ($product->isLockedAttribute('media')) { $product->unlockAttribute('media'); $wasLockedMedia = true; } $dateFieldFilters = []; $attributes = $product->getAttributes(); foreach ($attributes as $attrKey => $attribute) { if ($attribute->getBackend()->getType() == 'datetime') { if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') { $dateFieldFilters[$attrKey] = $this->getDateTimeFilter(); } } } $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData); $productData = $inputFilter->getUnescaped(); if (isset($productData['options'])) { $productOptions = $productData['options']; unset($productData['options']); } else { $productOptions = []; } $product->addData($productData); if ($wasLockedMedia) { $product->lockAttribute('media'); } if ($this->storeManager->hasSingleStore() && empty($product->getWebsiteIds())) { $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]); } /** * Check "Use Default Value" checkboxes values */ $useDefaults = (array) $this->request->getPost('use_default', []); foreach ($useDefaults as $attributeCode => $useDefaultState) { if ($useDefaultState) { $product->setData($attributeCode, null); } } $product = $this->setProductLinks($product); /** * Initialize product options */ if ($productOptions && !$product->getOptionsReadonly()) { // mark custom options that should to fall back to default value $options = $this->mergeProductOptions($productOptions, $this->request->getPost('options_use_default')); $customOptions = []; foreach ($options as $customOptionData) { if (empty($customOptionData['is_delete'])) { if (isset($customOptionData['values'])) { $customOptionData['values'] = array_filter($customOptionData['values'], function ($valueData) { return empty($valueData['is_delete']); }); } $customOption = $this->getCustomOptionFactory()->create(['data' => $customOptionData]); $customOption->setProductSku($product->getSku()); $customOption->setOptionId(null); $customOptions[] = $customOption; } } $product->setOptions($customOptions); } $product->setCanSaveCustomOptions(!empty($productData['affect_product_custom_options']) && !$product->getOptionsReadonly()); return $product; }
/** * @param Rule $rule * @param Product $product * @return $this * @throws \Exception * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function applyRule(Rule $rule, $product) { $ruleId = $rule->getId(); $productEntityId = $product->getId(); $websiteIds = array_intersect($product->getWebsiteIds(), $rule->getWebsiteIds()); if (!$rule->validate($product)) { return $this; } $this->connection->delete($this->resource->getTableName('catalogrule_product'), [$this->connection->quoteInto('rule_id = ?', $ruleId), $this->connection->quoteInto('product_id = ?', $productEntityId)]); $customerGroupIds = $rule->getCustomerGroupIds(); $fromTime = strtotime($rule->getFromDate()); $toTime = strtotime($rule->getToDate()); $toTime = $toTime ? $toTime + self::SECONDS_IN_DAY - 1 : 0; $sortOrder = (int) $rule->getSortOrder(); $actionOperator = $rule->getSimpleAction(); $actionAmount = $rule->getDiscountAmount(); $actionStop = $rule->getStopRulesProcessing(); $subActionOperator = $rule->getSubIsEnable() ? $rule->getSubSimpleAction() : ''; $subActionAmount = $rule->getSubDiscountAmount(); $rows = []; try { foreach ($websiteIds as $websiteId) { foreach ($customerGroupIds as $customerGroupId) { $rows[] = ['rule_id' => $ruleId, 'from_time' => $fromTime, 'to_time' => $toTime, 'website_id' => $websiteId, 'customer_group_id' => $customerGroupId, 'product_id' => $productEntityId, 'action_operator' => $actionOperator, 'action_amount' => $actionAmount, 'action_stop' => $actionStop, 'sort_order' => $sortOrder, 'sub_simple_action' => $subActionOperator, 'sub_discount_amount' => $subActionAmount]; if (count($rows) == $this->batchCount) { $this->connection->insertMultiple($this->getTable('catalogrule_product'), $rows); $rows = []; } } } if (!empty($rows)) { $this->connection->insertMultiple($this->resource->getTableName('catalogrule_product'), $rows); } } catch (\Exception $e) { throw $e; } $this->applyAllRules($product); return $this; }
/** * @param \Magento\Catalog\Model\Product $product * @return void */ private function assignProductToWebsites(\Magento\Catalog\Model\Product $product) { if (!$this->storeManager->hasSingleStore()) { if ($this->storeManager->getStore()->getCode() == \Magento\Store\Model\Store::ADMIN_CODE) { $websiteIds = array_keys($this->storeManager->getWebsites()); } else { $websiteIds = [$this->storeManager->getStore()->getWebsiteId()]; } $product->setWebsiteIds(array_unique(array_merge($product->getWebsiteIds(), $websiteIds))); } }
/** * Save product website relations * * @param \Magento\Catalog\Model\Product $product * @return $this */ protected function _saveWebsiteIds($product) { $websiteIds = $product->getWebsiteIds(); $oldWebsiteIds = array(); $product->setIsChangedWebsites(false); $adapter = $this->_getWriteAdapter(); $oldWebsiteIds = $this->getWebsiteIds($product); $insert = array_diff($websiteIds, $oldWebsiteIds); $delete = array_diff($oldWebsiteIds, $websiteIds); if (!empty($insert)) { $data = array(); foreach ($insert as $websiteId) { $data[] = array('product_id' => (int) $product->getId(), 'website_id' => (int) $websiteId); } $adapter->insertMultiple($this->_productWebsiteTable, $data); } if (!empty($delete)) { foreach ($delete as $websiteId) { $condition = array('product_id = ?' => (int) $product->getId(), 'website_id = ?' => (int) $websiteId); $adapter->delete($this->_productWebsiteTable, $condition); } } if (!empty($insert) || !empty($delete)) { $product->setIsChangedWebsites(true); } return $this; }
/** * Fill simple product data during generation * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Product $parentProduct * @param array $postData * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * * @return void */ protected function fillSimpleProductData(\Magento\Catalog\Model\Product $product, \Magento\Catalog\Model\Product $parentProduct, $postData) { $product->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID)->setTypeId($postData['weight'] ? ProductType::TYPE_SIMPLE : ProductType::TYPE_VIRTUAL)->setAttributeSetId($parentProduct->getNewVariationsAttributeSetId()); foreach ($product->getTypeInstance()->getSetAttributes($product) as $attribute) { if ($attribute->getIsUnique() || $attribute->getAttributeCode() == 'url_key' || $attribute->getFrontend()->getInputType() == 'gallery' || $attribute->getFrontend()->getInputType() == 'media_image' || !$attribute->getIsVisible()) { continue; } $product->setData($attribute->getAttributeCode(), $parentProduct->getData($attribute->getAttributeCode())); } $keysFilter = ['item_id', 'product_id', 'stock_id', 'type_id', 'website_id']; $postData['stock_data'] = array_diff_key((array) $parentProduct->getStockData(), array_flip($keysFilter)); if (!isset($postData['stock_data']['is_in_stock'])) { $stockStatus = $parentProduct->getQuantityAndStockStatus(); $postData['stock_data']['is_in_stock'] = $stockStatus['is_in_stock']; } $postData = $this->processMediaGallery($product, $postData); $postData['status'] = isset($postData['status']) ? $postData['status'] : \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED; $product->addData($postData)->setWebsiteIds($parentProduct->getWebsiteIds())->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE); }
/** * {@inheritdoc} */ public function getWebsiteIds() { $pluginInfo = $this->pluginList->getNext($this->subjectType, 'getWebsiteIds'); if (!$pluginInfo) { return parent::getWebsiteIds(); } else { return $this->___callPlugins('getWebsiteIds', func_get_args(), $pluginInfo); } }
/** * @param ComponentInterface $model * @param array $data * @param Product $product * @return void */ protected function setDataToModel(ComponentInterface $model, array $data, Product $product) { $model->setData($data)->setLinkType($data['type'])->setProductId($product->getData($this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()))->setStoreId($product->getStoreId())->setWebsiteId($product->getStore()->getWebsiteId())->setProductWebsiteIds($product->getWebsiteIds()); if (null === $model->getPrice()) { $model->setPrice(0); } if ($model->getIsUnlimited()) { $model->setNumberOfDownloads(0); } }
/** * Fill simple product data during generation * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Product $parentProduct * @param array $postData * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _fillSimpleProductData(\Magento\Catalog\Model\Product $product, \Magento\Catalog\Model\Product $parentProduct, $postData) { $product->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID)->setTypeId($postData['weight'] ? \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE : \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL)->setAttributeSetId($parentProduct->getNewVariationsAttributeSetId()); foreach ($product->getTypeInstance()->getEditableAttributes($product) as $attribute) { if ($attribute->getIsUnique() || $attribute->getAttributeCode() == 'url_key' || $attribute->getFrontend()->getInputType() == 'gallery' || $attribute->getFrontend()->getInputType() == 'media_image' || !$attribute->getIsVisible()) { continue; } $product->setData($attribute->getAttributeCode(), $parentProduct->getData($attribute->getAttributeCode())); } $postData['stock_data'] = $parentProduct->getStockData(); $postData['stock_data']['manage_stock'] = $postData['quantity_and_stock_status']['qty'] === '' ? 0 : 1; if (!isset($postData['stock_data']['is_in_stock'])) { $stockStatus = $parentProduct->getQuantityAndStockStatus(); $postData['stock_data']['is_in_stock'] = $stockStatus['is_in_stock']; } $configDefaultValue = $this->stockConfiguration->getManageStock($product->getStoreId()); $postData['stock_data']['use_config_manage_stock'] = $postData['stock_data']['manage_stock'] == $configDefaultValue ? 1 : 0; if (!empty($postData['image'])) { $postData['small_image'] = $postData['thumbnail'] = $postData['image']; $postData['media_gallery']['images'][] = ['position' => 1, 'file' => $postData['image'], 'disabled' => 0, 'label' => '']; } $product->addData($postData)->setWebsiteIds($parentProduct->getWebsiteIds())->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE); }
/** * Prepare product to save * * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $product * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $product) { if ($downloadable = $this->request->getPost('downloadable')) { $product->setDownloadableData($downloadable); $extension = $product->getExtensionAttributes(); if (isset($downloadable['link']) && is_array($downloadable['link'])) { $links = []; foreach ($downloadable['link'] as $linkData) { if (!$linkData || isset($linkData['is_delete']) && (bool) $linkData['is_delete']) { continue; } else { unset($linkData['link_id']); // TODO: need to implement setLinkFileContent() $link = $this->linkFactory->create(['data' => $linkData]); if (isset($linkData['type'])) { $link->setLinkType($linkData['type']); } if (isset($linkData['file'])) { $link->setLinkFile($linkData['file']); } if (isset($linkData['file_content'])) { $link->setLinkFileContent($linkData['file_content']); } $link->setId(null); if (isset($linkData['sample']['type'])) { $link->setSampleType($linkData['sample']['type']); } if (isset($linkData['sample']['file'])) { $link->setSampleFile($linkData['sample']['file']); } if (isset($linkData['sample']['url'])) { $link->setSampleUrl($linkData['sample']['url']); } if (isset($linkData['sample']['file_content'])) { $link->setSampleFileContent($linkData['file_content']); } $link->setStoreId($product->getStoreId()); $link->setWebsiteId($product->getStore()->getWebsiteId()); $link->setProductWebsiteIds($product->getWebsiteIds()); if (!$link->getSortOrder()) { $link->setSortOrder(1); } if (null === $link->getPrice()) { $link->setPrice(0); } if ($link->getIsUnlimited()) { $link->setNumberOfDownloads(0); } $links[] = $link; } } $extension->setDownloadableProductLinks($links); } if (isset($downloadable['sample']) && is_array($downloadable['sample'])) { $samples = []; foreach ($downloadable['sample'] as $sampleData) { if (!$sampleData || isset($sampleData['is_delete']) && (bool) $sampleData['is_delete']) { continue; } else { unset($sampleData['sample_id']); $sample = $this->sampleFactory->create(['data' => $sampleData]); $sample->setId(null); $sample->setStoreId($product->getStoreId()); if (isset($sampleData['type'])) { $sample->setSampleType($sampleData['type']); } if (isset($sampleData['sample_url'])) { $sample->setSampleUrl($sampleData['sample_url']); } if (!$sample->getSortOrder()) { $sample->setSortOrder(1); } $samples[] = $sample; } } $extension->setDownloadableProductSamples($samples); } $product->setExtensionAttributes($extension); if ($product->getLinksPurchasedSeparately()) { $product->setTypeHasRequiredOptions(true)->setRequiredOptions(true); } else { $product->setTypeHasRequiredOptions(false)->setRequiredOptions(false); } } return $product; }