/** * Set inventory data to custom attribute * * @param Product $object * @return $this */ public function afterLoad($object) { $stockItem = $this->stockRegistry->getStockItem($object->getId(), $object->getStore()->getWebsiteId()); $object->setData($this->getAttribute()->getAttributeCode(), ['is_in_stock' => $stockItem->getIsInStock(), 'qty' => $stockItem->getQty()]); return parent::afterLoad($object); }
/** * @covers \Magento\Bundle\Pricing\Price\TierPrice::isFirstPriceBetter * @dataProvider providerForGetterTierPriceList */ public function testGetterTierPriceList($tierPrices, $basePrice, $expectedResult) { $this->product->setData(TierPrice::PRICE_CODE, $tierPrices); $price = $this->getMock('Magento\\Framework\\Pricing\\Price\\PriceInterface'); $price->expects($this->any())->method('getValue')->will($this->returnValue($basePrice)); $this->priceInfo->expects($this->any())->method('getPrice')->will($this->returnValue($price)); $this->calculator->expects($this->atLeastOnce())->method('getAmount')->will($this->returnArgument(0)); $this->assertEquals($expectedResult, $this->model->getTierPriceList()); $this->assertEquals(count($expectedResult), $this->model->getTierPriceCount()); }
/** * @covers \Magento\Bundle\Pricing\Price\TierPrice::isFirstPriceBetter * @dataProvider providerForGetterTierPriceList */ public function testGetterTierPriceList($tierPrices, $basePrice, $expectedResult) { $this->product->setData(TierPrice::PRICE_CODE, $tierPrices); $price = $this->getMock('Magento\\Framework\\Pricing\\Price\\PriceInterface'); $price->expects($this->any())->method('getValue')->will($this->returnValue($basePrice)); $this->priceInfo->expects($this->any())->method('getPrice')->will($this->returnValue($price)); $this->calculator->expects($this->atLeastOnce())->method('getAmount')->will($this->returnArgument(0)); $this->priceCurrencyMock->expects($this->never())->method('convertAndRound'); $group = $this->getMock('\\Magento\\Customer\\Model\\Data\\Group', [], [], '', false); $group->expects($this->any())->method('getId')->willReturn(\Magento\Customer\Model\GroupManagement::CUST_GROUP_ALL); $this->groupManagement->expects($this->any())->method('getAllCustomersGroup')->will($this->returnValue($group)); $this->assertEquals($expectedResult, $this->model->getTierPriceList()); $this->assertEquals(count($expectedResult), $this->model->getTierPriceCount()); }
public function testGetCustomAttributes() { $priceCode = 'price'; $colorAttributeCode = 'color'; $interfaceAttribute = $this->getMock('\\Magento\\Framework\\Api\\MetadataObjectInterface'); $interfaceAttribute->expects($this->once())->method('getAttributeCode')->willReturn($priceCode); $colorAttribute = $this->getMock('\\Magento\\Framework\\Api\\MetadataObjectInterface'); $colorAttribute->expects($this->once())->method('getAttributeCode')->willReturn($colorAttributeCode); $customAttributesMetadata = [$interfaceAttribute, $colorAttribute]; $this->metadataServiceMock->expects($this->once())->method('getCustomAttributesMetadata')->willReturn($customAttributesMetadata); $this->model->setData($priceCode, 10); //The color attribute is not set, expect empty custom attribute array $this->assertEquals([], $this->model->getCustomAttributes()); //Set the color attribute; $this->model->setData($colorAttributeCode, "red"); $attributeValue = new \Magento\Framework\Api\AttributeValue(); $attributeValue2 = new \Magento\Framework\Api\AttributeValue(); $this->attributeValueFactory->expects($this->exactly(2))->method('create')->willReturnOnConsecutiveCalls($attributeValue, $attributeValue2); $this->assertEquals(1, count($this->model->getCustomAttributes())); $this->assertNotNull($this->model->getCustomAttribute($colorAttributeCode)); $this->assertEquals("red", $this->model->getCustomAttribute($colorAttributeCode)->getValue()); //Change the attribute value, should reflect in getCustomAttribute $this->model->setData($colorAttributeCode, "blue"); $this->assertEquals(1, count($this->model->getCustomAttributes())); $this->assertNotNull($this->model->getCustomAttribute($colorAttributeCode)); $this->assertEquals("blue", $this->model->getCustomAttribute($colorAttributeCode)->getValue()); }
/** * @covers \Magento\Catalog\Model\Product::getCalculatedFinalPrice * @covers \Magento\Catalog\Model\Product::getMinimalPrice * @covers \Magento\Catalog\Model\Product::getSpecialPrice * @covers \Magento\Catalog\Model\Product::getSpecialFromDate * @covers \Magento\Catalog\Model\Product::getSpecialToDate * @covers \Magento\Catalog\Model\Product::getRequestPath * @covers \Magento\Catalog\Model\Product::getGiftMessageAvailable * @dataProvider getObsoleteGettersDataProvider * @param string $key * @param string $method */ public function testGetObsoleteGetters($key, $method) { $value = uniqid(); $this->assertEmpty($this->_model->{$method}()); $this->_model->setData($key, $value); $this->assertEquals($value, $this->_model->{$method}()); }
/** * @param \Magento\Catalog\Model\Product $product * @param int|string $customerGroupId * @param int $qty * @param int $websiteId * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\CouldNotSaveException * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function removeTierPrice(\Magento\Catalog\Model\Product $product, $customerGroupId, $qty, $websiteId) { $prices = $product->getData('tier_price'); // verify if price exist if ($prices === null) { throw new NoSuchEntityException(__('This product doesn\'t have tier price')); } $tierPricesQty = count($prices); foreach ($prices as $key => $tierPrice) { if ($customerGroupId == 'all' && $tierPrice['price_qty'] == $qty && $tierPrice['all_groups'] == 1 && intval($tierPrice['website_id']) === intval($websiteId)) { unset($prices[$key]); } elseif ($tierPrice['price_qty'] == $qty && $tierPrice['cust_group'] == $customerGroupId && intval($tierPrice['website_id']) === intval($websiteId)) { unset($prices[$key]); } } if ($tierPricesQty == count($prices)) { throw new NoSuchEntityException(__('Product hasn\'t group price with such data: customerGroupId = \'%1\'' . ', website = %2, qty = %3', [$customerGroupId, $websiteId, $qty])); } $product->setData('tier_price', $prices); try { $this->productRepository->save($product); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for tier_price')); } }
public function testGetIsSalableHasDataIsSaleable() { $typeInstanceMock = $this->getMock('Magento\\Catalog\\Model\\Product\\Type\\Simple', [], [], '', false); $this->model->setTypeInstance($typeInstanceMock); $this->model->setData('is_saleable', true); $this->model->setData('is_salable', false); self::assertTrue($this->model->getIsSalable()); }
/** * Implode data for validation * * @param \Magento\Catalog\Model\Product $object * @return bool */ public function validate($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); $data = $object->getData($attributeCode); if (is_array($data)) { $object->setData($attributeCode, implode(',', array_filter($data))); } return parent::validate($object); }
/** * Initialize product before saving * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function initialize(\Magento\Catalog\Model\Product $product) { $productData = $this->request->getPost('product'); 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); } foreach (['category_ids', 'website_ids'] as $field) { if (!isset($productData[$field])) { $productData[$field] = []; } } $wasLockedMedia = false; if ($product->isLockedAttribute('media')) { $product->unlockAttribute('media'); $wasLockedMedia = true; } $product->addData($productData); if ($wasLockedMedia) { $product->lockAttribute('media'); } if ($this->storeManager->hasSingleStore()) { $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]); } /** * Check "Use Default Value" checkboxes values */ $useDefaults = $this->request->getPost('use_default'); if ($useDefaults) { foreach ($useDefaults as $attributeCode) { $product->setData($attributeCode, false); } } $links = $this->request->getPost('links'); $links = is_array($links) ? $links : []; $linkTypes = ['related', 'upsell', 'crosssell']; foreach ($linkTypes as $type) { if (isset($links[$type])) { $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]); } } $product = $this->productLinks->initializeLinks($product, $links); /** * Initialize product options */ if (isset($productData['options']) && !$product->getOptionsReadonly()) { // mark custom options that should to fall back to default value $options = $this->mergeProductOptions($productData['options'], $this->request->getPost('options_use_default')); $product->setProductOptions($options); } $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly()); return $product; }
protected function prepareProducts() { $product = $this->product->loadByAttribute('sku', 'simple'); $product->load($product->getId()); $this->product = $product; $this->product->setData('test_attribute', 'test_attribute_value')->save(); $this->productSecond = clone $this->product; $this->productSecond->setId(null)->setUrlKey('product-second')->save(); $this->productThird = clone $this->product; $this->productThird->setId(null)->setUrlKey('product-third')->setData('test_attribute', 'NO_test_attribute_value')->save(); }
/** * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $result * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $result) { $productData = $this->request->getPost('product'); /** * Create Permanent Redirect for old URL key */ if ($result->getId() && isset($productData['url_key_create_redirect'])) { $result->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']); } return $result; }
/** * @dataProvider getIdentitiesProvider * @param array $expected * @param array $origData * @param array $data * @param bool $isDeleted */ public function testGetIdentities($expected, $origData, $data, $isDeleted = false) { $this->model->setIdFieldName('id'); if (is_array($origData)) { foreach ($origData as $key => $value) { $this->model->setOrigData($key, $value); } } $this->model->setData($data); $this->model->isDeleted($isDeleted); $this->assertEquals($expected, $this->model->getIdentities()); }
/** * @param Product $product * @param array $mediaEntries * @return void */ public function addMediaDataToProduct(Product $product, array $mediaEntries) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = []; $value['images'] = []; $value['values'] = []; foreach ($mediaEntries as $mediaEntry) { $mediaEntry = $this->substituteNullsWithDefaultValues($mediaEntry); $value['images'][$mediaEntry['value_id']] = $mediaEntry; } $product->setData($attrCode, $value); }
/** * */ public function testReindexRowAfterEdit() { $this->indexer->reindexAll(); $this->productApple->setData('name', 'Simple Product Cucumber'); $this->productApple->save(); $products = $this->search('Apple'); $this->assertCount(0, $products); $products = $this->search('Cucumber'); $this->assertCount(1, $products); $this->assertEquals($this->productApple->getId(), $products[0]->getId()); $products = $this->search('Simple Product'); $this->assertCount(5, $products); }
/** * @depends testReindexAll */ public function testReindexRowAfterEdit() { $this->productFirst->setData('name', 'Simple Product Third'); $this->productFirst->save(); $products = $this->search('Simple Product First'); $this->assertCount(0, $products); $products = $this->search('Simple Product Third'); $this->assertCount(1, $products); $this->assertEquals($this->productFirst->getId(), $products[0]->getId()); $products = $this->search('Simple Product'); $this->assertCount(2, $products); $this->assertEquals($this->productFirst->getId(), $products[0]->getId()); $this->assertEquals($this->productSecond->getId(), $products[1]->getId()); }
/** * testGetTierPrices * testSetTierPrices * * @dataProvider pricesDataProvider */ public function testTierPrices($priceScope, $expectedWebsiteId) { // establish the behavior of the mocks $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue($priceScope)); $this->websiteMock->expects($this->any())->method('getId')->will($this->returnValue($expectedWebsiteId)); $this->tpFactory->expects($this->any())->method('create')->will($this->returnCallback(function () { return $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product\\TierPrice'); })); // create sample TierPrice objects that would be coming from a REST call $tp1 = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product\\TierPrice'); $tp1->setValue(10); $tp1->setCustomerGroupId(1); $tp1->setQty(11); $tp2 = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product\\TierPrice'); $tp2->setValue(20); $tp2->setCustomerGroupId(2); $tp2->setQty(22); $tps = [$tp1, $tp2]; // force the product to have null tier prices $this->product->setData($this::KEY_TIER_PRICE, null); $this->assertNull($this->product->getData($this::KEY_TIER_PRICE)); // set the product with the TierPrice objects $this->model->setTierPrices($this->product, $tps); // test the data actually set on the product $tpArray = $this->product->getData($this::KEY_TIER_PRICE); $this->assertNotNull($tpArray); $this->assertTrue(is_array($tpArray)); $this->assertEquals(sizeof($tps), sizeof($tpArray)); for ($i = 0; $i < sizeof($tps); $i++) { $tpData = $tpArray[$i]; $this->assertEquals($expectedWebsiteId, $tpData['website_id'], 'Website Id does not match'); $this->assertEquals($tps[$i]->getValue(), $tpData['price'], 'Price/Value does not match'); $this->assertEquals($tps[$i]->getValue(), $tpData['website_price'], 'WebsitePrice/Value does not match'); $this->assertEquals($tps[$i]->getCustomerGroupId(), $tpData['cust_group'], 'Customer group Id does not match'); $this->assertEquals($tps[$i]->getQty(), $tpData['price_qty'], 'Qty does not match'); } // test with the data retrieved as a REST object $tpRests = $this->model->getTierPrices($this->product); $this->assertNotNull($tpRests); $this->assertTrue(is_array($tpRests)); $this->assertEquals(sizeof($tps), sizeof($tpRests)); for ($i = 0; $i < sizeof($tps); $i++) { $this->assertEquals($tps[$i]->getValue(), $tpRests[$i]->getValue(), 'REST: Price/Value does not match'); $this->assertEquals($tps[$i]->getCustomerGroupId(), $tpRests[$i]->getCustomerGroupId(), 'REST: Customer group Id does not match'); $this->assertEquals($tps[$i]->getQty(), $tpRests[$i]->getQty(), 'REST: Qty does not match'); } }
/** * @magentoAppArea frontend */ public function testReset() { $model = $this->_model; $this->_assertEmpty($model); $this->_model->setData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->setOrigData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->addCustomOption('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->canAffectOptions(true); $this->_model->reset(); $this->_assertEmpty($model); }
/** * */ public function testReindexRowAfterEdit() { $this->testReindexAll(); $this->productApple->setData('name', 'Simple Product Cucumber'); $this->productApple->save(); $products = $this->search('Apple'); $this->assertCount(0, $products); $products = $this->search('Cucumber'); $this->assertCount(1, $products); $this->assertEquals($this->productApple->getId(), $products[0]->getId()); $products = $this->search('Simple Product'); $this->assertCount(5, $products); $this->assertEquals($this->productApple->getId(), $products[0]->getId()); $this->assertEquals($this->productBanana->getId(), $products[1]->getId()); $this->assertEquals($this->productOrange->getId(), $products[2]->getId()); $this->assertEquals($this->productPapaya->getId(), $products[3]->getId()); $this->assertEquals($this->productCherry->getId(), $products[4]->getId()); }
/** * @magentoAppArea frontend */ public function testReset() { $model = $this->_model; $this->_assertEmpty($model); $this->_model->setData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->setOrigData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->addCustomOption('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->addOption(\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product\\Option')); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->canAffectOptions(true); $this->_model->reset(); $this->_assertEmpty($model); }
/** * Set media attribute value * * @param \Magento\Catalog\Model\Product $product * @param string|string[] $mediaAttribute * @param string $value * @return $this */ public function setMediaAttribute(\Magento\Catalog\Model\Product $product, $mediaAttribute, $value) { $mediaAttributeCodes = array_keys($product->getMediaAttributes()); if (is_array($mediaAttribute)) { foreach ($mediaAttribute as $atttribute) { if (in_array($atttribute, $mediaAttributeCodes)) { $product->setData($atttribute, $value); } } } elseif (in_array($mediaAttribute, $mediaAttributeCodes)) { $product->setData($mediaAttribute, $value); } return $this; }
/** * After Save Attribute manipulation * * @param \Magento\Catalog\Model\Product $object * @return $this */ public function afterSave($object) { $websiteId = $this->_storeManager->getStore($object->getStoreId())->getWebsiteId(); $isGlobal = $this->getAttribute()->isScopeGlobal() || $websiteId == 0; $priceRows = $object->getData($this->getAttribute()->getName()); if (empty($priceRows)) { if ($isGlobal) { $this->_getResource()->deletePriceData($object->getId()); } else { $this->_getResource()->deletePriceData($object->getId(), $websiteId); } return $this; } $old = array(); $new = array(); // prepare original data for compare $origGroupPrices = $object->getOrigData($this->getAttribute()->getName()); if (!is_array($origGroupPrices)) { $origGroupPrices = array(); } foreach ($origGroupPrices as $data) { if ($data['website_id'] > 0 || $data['website_id'] == '0' && $isGlobal) { $key = join('-', array_merge(array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data))); $old[$key] = $data; } } // prepare data for save foreach ($priceRows as $data) { $hasEmptyData = false; foreach ($this->_getAdditionalUniqueFields($data) as $field) { if (empty($field)) { $hasEmptyData = true; break; } } if ($hasEmptyData || !isset($data['cust_group']) || !empty($data['delete'])) { continue; } if ($this->getAttribute()->isScopeGlobal() && $data['website_id'] > 0) { continue; } if (!$isGlobal && (int) $data['website_id'] == 0) { continue; } $key = join('-', array_merge(array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data))); $useForAllGroups = $data['cust_group'] == CustomerGroupServiceInterface::CUST_GROUP_ALL; $customerGroupId = !$useForAllGroups ? $data['cust_group'] : 0; $new[$key] = array_merge(array('website_id' => $data['website_id'], 'all_groups' => $useForAllGroups ? 1 : 0, 'customer_group_id' => $customerGroupId, 'value' => $data['price']), $this->_getAdditionalUniqueFields($data)); } $delete = array_diff_key($old, $new); $insert = array_diff_key($new, $old); $update = array_intersect_key($new, $old); $isChanged = false; $productId = $object->getId(); if (!empty($delete)) { foreach ($delete as $data) { $this->_getResource()->deletePriceData($productId, null, $data['price_id']); $isChanged = true; } } if (!empty($insert)) { foreach ($insert as $data) { $price = new \Magento\Framework\Object($data); $price->setEntityId($productId); $this->_getResource()->savePriceData($price); $isChanged = true; } } if (!empty($update)) { foreach ($update as $k => $v) { if ($old[$k]['price'] != $v['value']) { $price = new \Magento\Framework\Object(array('value_id' => $old[$k]['price_id'], 'value' => $v['value'])); $this->_getResource()->savePriceData($price); $isChanged = true; } } } if ($isChanged) { $valueChangedKey = $this->getAttribute()->getName() . '_changed'; $object->setData($valueChangedKey, 1); } return $this; }
/** * 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 Product $object * @return Product * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function beforeSave($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if (!is_array($value) || !isset($value['images'])) { return $object; } if (!is_array($value['images']) && strlen($value['images']) > 0) { $value['images'] = $this->jsonHelper->jsonDecode($value['images']); } if (!is_array($value['images'])) { $value['images'] = []; } $clearImages = []; $newImages = []; $existImages = []; if ($object->getIsDuplicate() != true) { foreach ($value['images'] as &$image) { if (!empty($image['removed'])) { $clearImages[] = $image['file']; } elseif (empty($image['value_id'])) { $newFile = $this->moveImageFromTmp($image['file']); $image['new_file'] = $newFile; $newImages[$image['file']] = $image; $image['file'] = $newFile; } else { $existImages[$image['file']] = $image; } } } else { // For duplicating we need copy original images. $duplicate = []; foreach ($value['images'] as &$image) { if (empty($image['value_id'])) { continue; } $duplicate[$image['value_id']] = $this->copyImage($image['file']); $image['new_file'] = $duplicate[$image['value_id']]; $newImages[$image['file']] = $image; } $value['duplicate'] = $duplicate; } foreach ($object->getMediaAttributes() as $mediaAttribute) { $mediaAttrCode = $mediaAttribute->getAttributeCode(); $attrData = $object->getData($mediaAttrCode); if (in_array($attrData, $clearImages)) { $object->setData($mediaAttrCode, 'no_selection'); } if (in_array($attrData, array_keys($newImages))) { $object->setData($mediaAttrCode, $newImages[$attrData]['new_file']); $object->setData($mediaAttrCode . '_label', $newImages[$attrData]['label']); } if (in_array($attrData, array_keys($existImages))) { $object->setData($mediaAttrCode . '_label', $existImages[$attrData]['label']); } } $object->setData($attrCode, $value); return $object; }
/** * Set store filter for associated products * * @param $store int|\Magento\Store\Model\Store * @param \Magento\Catalog\Model\Product $product * @return $this */ public function setStoreFilter($store, $product) { $cacheKey = '_cache_instance_store_filter'; $product->setData($cacheKey, $store); return $this; }
public function testIsSalable() { $this->product->expects($this->any())->method('getStatus')->will($this->returnValue(Status::STATUS_ENABLED)); $this->product->setData('is_salable', 3); $this->assertEquals(true, $this->model->isSalable($this->product)); }
/** * Initialize product before saving * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function initialize(\Magento\Catalog\Model\Product $product) { $productData = $this->request->getPost('product'); 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); } foreach (['category_ids', 'website_ids'] as $field) { if (!isset($productData[$field])) { $productData[$field] = []; } } $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->dateFilter; } } } $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData); $productData = $inputFilter->getUnescaped(); $product->addData($productData); if ($wasLockedMedia) { $product->lockAttribute('media'); } if ($this->storeManager->hasSingleStore()) { $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]); } /** * Check "Use Default Value" checkboxes values */ $useDefaults = $this->request->getPost('use_default'); if ($useDefaults) { foreach ($useDefaults as $attributeCode) { $product->setData($attributeCode, false); } } $links = $this->request->getPost('links'); $links = is_array($links) ? $links : []; $linkTypes = ['related', 'upsell', 'crosssell']; foreach ($linkTypes as $type) { if (isset($links[$type])) { $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]); } } $product = $this->productLinks->initializeLinks($product, $links); $productLinks = $product->getProductLinks(); $linkTypes = ['related' => $product->getRelatedReadonly(), 'upsell' => $product->getUpsellReadonly(), 'crosssell' => $product->getCrosssellReadonly()]; foreach ($linkTypes as $linkType => $readonly) { if (isset($links[$linkType]) && !$readonly) { foreach ($links[$linkType] as $linkId => $linkData) { $linkProduct = $this->productRepository->getById($linkId); $link = $this->productLinkFactory->create(); $link->setSku($product->getSku())->setLinkedProductSku($linkProduct->getSku())->setLinkType($linkType)->setPosition(isset($linkData['position']) ? (int) $linkData['position'] : 0); $productLinks[] = $link; } } } $product->setProductLinks($productLinks); /** * Initialize product options */ if (isset($productData['options']) && !$product->getOptionsReadonly()) { // mark custom options that should to fall back to default value $options = $this->mergeProductOptions($productData['options'], $this->request->getPost('options_use_default')); $customOptions = []; foreach ($options as $customOptionData) { if (!(bool) $customOptionData['is_delete']) { $customOption = $this->customOptionFactory->create(['data' => $customOptionData]); $customOption->setProductSku($product->getSku()); $customOption->setOptionId(null); $customOptions[] = $customOption; } } $product->setOptions($customOptions); } $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly()); return $product; }
/** * Set only saleable filter * * @param \Magento\Catalog\Model\Product $product * @return $this */ public function setSaleableStatus($product) { $product->setData($this->_keyStatusFilters, $this->_catalogProductStatus->getSaleableStatusIds()); return $this; }
/** * Retrieve bundle options collection based on ids * * @param array $optionIds * @param \Magento\Catalog\Model\Product $product * @return \Magento\Bundle\Model\ResourceModel\Option\Collection */ public function getOptionsByIds($optionIds, $product) { sort($optionIds); $usedOptions = $product->getData($this->_keyUsedOptions); $usedOptionsIds = $product->getData($this->_keyUsedOptionsIds); if (!$usedOptions || serialize($usedOptionsIds) != serialize($optionIds)) { $usedOptions = $this->_bundleOption->create()->getResourceCollection()->setProductIdFilter($product->getId())->setPositionOrder()->joinValues($this->_storeManager->getStore()->getId())->setIdFilter($optionIds); $product->setData($this->_keyUsedOptions, $usedOptions); $product->setData($this->_keyUsedOptionsIds, $optionIds); } return $usedOptions; }
/** * Initialize product before saving * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product */ public function initialize(\Magento\Catalog\Model\Product $product) { $productData = $this->request->getPost('product'); if ($productData) { $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : array(); $productData['stock_data'] = $this->stockFilter->filter($stockData); } foreach (array('category_ids', 'website_ids') as $field) { if (!isset($productData[$field])) { $productData[$field] = array(); } } $wasLockedMedia = false; if ($product->isLockedAttribute('media')) { $product->unlockAttribute('media'); $wasLockedMedia = true; } $product->addData($productData); if ($wasLockedMedia) { $product->lockAttribute('media'); } if ($this->storeManager->hasSingleStore()) { $product->setWebsiteIds(array($this->storeManager->getStore(true)->getWebsite()->getId())); } /** * Create Permanent Redirect for old URL key */ if ($product->getId() && isset($productData['url_key_create_redirect'])) { $product->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']); } /** * Check "Use Default Value" checkboxes values */ $useDefaults = $this->request->getPost('use_default'); if ($useDefaults) { foreach ($useDefaults as $attributeCode) { $product->setData($attributeCode, false); } } $links = $this->request->getPost('links'); $links = is_array($links) ? $links : array(); $linkTypes = array('related', 'upsell', 'crosssell'); foreach ($linkTypes as $type) { if (isset($links[$type])) { $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]); } } $product = $this->productLinks->initializeLinks($product, $links); /** * Initialize product options */ if (isset($productData['options']) && !$product->getOptionsReadonly()) { $product->setProductOptions($productData['options']); } $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly()); return $product; }
public function testGetStoreId() { $this->assertEquals($this->objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getId(), $this->_model->getStoreId()); $this->_model->setData('store_id', 999); $this->assertEquals(999, $this->_model->getStoreId()); }