public function testSetUsedProductAttributeIds() { $testConfigurable = $this->_getAttributeByCode('test_configurable'); $this->_model->setUsedProductAttributeIds([$testConfigurable->getId()], $this->_product); $attributes = $this->_product->getData('_cache_instance_configurable_attributes'); $this->assertArrayHasKey(0, $attributes); $this->assertInstanceOf('Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable\\Attribute', $attributes[0]); $this->assertSame($testConfigurable, $attributes[0]->getProductAttribute()); }
/** * @param \Magento\Catalog\Model\Product $product * @return mixed */ public function getValueByProductInstance(\Magento\Catalog\Model\Product $product) { $status = $product->getData('amazon_status'); $variationChildStatuses = $product->getData('variation_child_statuses'); if ($product->getData('is_variation_parent') && !empty($variationChildStatuses)) { $status = json_decode($variationChildStatuses, true); } return $status; }
public function getValueByProductInstance(\Magento\Catalog\Model\Product $product) { $minPrice = $product->getData('min_online_price'); $maxPrice = $product->getData('max_online_price'); if (!empty($minPrice) && !empty($maxPrice) && $minPrice != $maxPrice) { return array($product->getData('min_online_price'), $product->getData('max_online_price')); } return $product->getData('min_online_price'); }
public function beforeProcess() { $product = $this->getEvent()->getProduct(); if (!$product instanceof \Magento\Catalog\Model\Product) { throw new \Ess\M2ePro\Model\Exception('Product event doesn\'t have correct Product instance.'); } $this->product = $product; $this->productId = (int) $this->product->getId(); $this->storeId = (int) $this->product->getData('store_id'); }
/** * @param UrlRewrite $url * @param int $storeId * @param Category|null $category * @return array */ protected function generateForAutogenerated($url, $storeId, $category) { if (!$this->product->getData('save_rewrites_history')) { return []; } $targetPath = $this->productUrlPathGenerator->getUrlPathWithSuffix($this->product, $storeId, $category); if ($url->getRequestPath() === $targetPath) { return []; } return [$this->urlRewriteFactory->create()->setEntityType(ProductUrlRewriteGenerator::ENTITY_TYPE)->setEntityId($this->product->getId())->setRequestPath($url->getRequestPath())->setTargetPath($targetPath)->setRedirectType(OptionProvider::PERMANENT)->setStoreId($storeId)->setDescription($url->getDescription())->setIsAutogenerated(0)->setMetadata($url->getMetadata())]; }
/** * @param \Magento\Catalog\Model\Product $product * @return int */ public function getValueByProductInstance(\Magento\Catalog\Model\Product $product) { $generalId = $product->getData('general_id'); if (!empty($generalId)) { return \Ess\M2ePro\Model\Amazon\Listing\Product::GENERAL_ID_STATE_SET; } if ($product->getData('is_general_id_owner') == 1) { return \Ess\M2ePro\Model\Amazon\Listing\Product::GENERAL_ID_STATE_READY_FOR_NEW_ASIN; } $searchStatusActionRequired = \Ess\M2ePro\Model\Amazon\Listing\Product::SEARCH_SETTINGS_STATUS_ACTION_REQUIRED; $searchStatusNotFound = \Ess\M2ePro\Model\Amazon\Listing\Product::SEARCH_SETTINGS_STATUS_NOT_FOUND; if ($product->getData('search_settings_status') == $searchStatusActionRequired || $product->getData('search_settings_status') == $searchStatusNotFound) { return \Ess\M2ePro\Model\Amazon\Listing\Product::GENERAL_ID_STATE_ACTION_REQUIRED; } return \Ess\M2ePro\Model\Amazon\Listing\Product::GENERAL_ID_STATE_NOT_SET; }
/** * @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')); } }
/** * @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 */ public function removeTierPrice(\Magento\Catalog\Model\Product $product, $customerGroupId, $qty, $websiteId) { $prices = $product->getData('tier_price'); // verify if price exist if (is_null($prices)) { 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 = '{$customerGroupId}'," . "website = {$websiteId}, qty = {$qty}"); } $product->setData('tier_price', $prices); try { $product->save(); } catch (\Exception $exception) { throw new CouldNotSaveException("Invalid data provided for tier_price"); } }
/** * 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; }
/** * 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; }
/** * Return product image label * * @return string */ public function getLabel() { $label = $this->_product->getData($this->getType() . self::VAR_NAME_SEPARATOR . 'label'); if (empty($label)) { $label = $this->_product->getName(); } return $label; }
/** * Retrieve Product Url path (with category if exists) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Category $category * * @return string */ public function getUrlPath($product, $category = null) { $path = $product->getData('url_path'); if ($path === null) { $path = $this->generateUrlKey($product); } return $category === null ? $path : $this->categoryUrlPathGenerator->getUrlPath($category) . '/' . $path; }
/** * Return image label * * @return string */ public function getLabel() { $label = $this->_product->getData($this->getType() . '_' . 'label'); if (empty($label)) { $label = $this->_product->getName(); } return $label; }
/** * Retrieve Product Url path (with category if exists) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Category $category * * @return string */ public function getUrlPath($product, $category = null) { $path = $product->getData('url_path'); if ($path === null) { $path = $product->getUrlKey() === false ? $this->prepareProductDefaultUrlKey($product) : $this->prepareProductUrlKey($product); } return $category === null ? $path : $this->categoryUrlPathGenerator->getUrlPath($category) . '/' . $path; }
/** * Returns url to product image * * @param \Magento\Catalog\Model\Product $product * * @return string|false */ public function getUrl($product) { $image = $product->getData($this->getAttribute()->getAttributeCode()); $url = false; if (!empty($image)) { $url = $this->_storeManager->getStore($product->getStore())->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product/' . $image; } return $url; }
/** * @param \Magento\Catalog\Model\Product $product * @param \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute * @return array */ protected function getMediaEntriesDataCollection(\Magento\Catalog\Model\Product $product, \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $attribute) { $attributeCode = $attribute->getAttributeCode(); $mediaData = $product->getData($attributeCode); if (!empty($mediaData['images']) && is_array($mediaData['images'])) { return $mediaData['images']; } return []; }
/** * Validate * * @param \Magento\Catalog\Model\Product $object * @throws \Magento\Framework\Model\Exception * @return bool */ public function validate($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if (!empty($value) && !\Zend_Validate::is($value, 'Between', array('min' => 0, 'max' => 99999999.9999))) { throw new \Magento\Framework\Model\Exception(__('Please enter a number 0 or greater in this field.')); } return true; }
/** * Validate * * @param Product $object * @throws \Magento\Framework\Exception\LocalizedException * @return bool */ public function validate($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if (!empty($value['qty']) && !preg_match('/^-?\\d*(\\.|,)?\\d{0,4}$/i', $value['qty'])) { throw new \Magento\Framework\Exception\LocalizedException(__('Please enter a valid number in this field.')); } return true; }
public function getValueByProductInstance(\Magento\Catalog\Model\Product $product) { $startDate = $product->getData('start_date'); if (empty($startDate)) { return null; } $startDate = new \DateTime($startDate); return strtotime($startDate->format('Y-m-d')); }
/** * 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); }
/** * Validate * * @param \Magento\Catalog\Model\Product $object * @throws \Magento\Framework\Exception\LocalizedException * @return bool */ public function validate($object) { $attrCode = $this->getAttribute()->getAttributeCode(); $value = $object->getData($attrCode); if (!$this->isPositiveOrZero($value)) { throw new \Magento\Framework\Exception\LocalizedException(__('Please enter a number 0 or greater in this field.')); } return true; }
public function testStatusAfterLoad() { $this->resource->expects($this->once())->method('load')->with($this->model, 1, null); $this->eventManagerMock->expects($this->exactly(4))->method('dispatch'); $this->model->load(1); $this->assertEquals(Status::STATUS_ENABLED, $this->model->getData(\Magento\Catalog\Model\Product::STATUS)); $this->assertFalse($this->model->hasDataChanges()); $this->model->setStatus(Status::STATUS_DISABLED); $this->assertTrue($this->model->hasDataChanges()); }
/** * @param Product $product * @param Product $bundle * @return Metadata */ public function createDataFromModel(Product $product, Product $bundle) { $selectionPriceType = $selectionPrice = null; /** @var \Magento\Bundle\Model\Selection $product */ if ($bundle->getPriceType()) { $selectionPriceType = $product->getSelectionPriceType(); $selectionPrice = $product->getSelectionPriceValue(); } $this->builder->populateWithArray($product->getData())->setDefault($product->getIsDefault())->setQty($product->getSelectionQty())->setDefined($product->getSelectionCanChangeQty())->setPrice($selectionPrice)->setPriceType($selectionPriceType); return $this->builder->create(); }
public function getValueByProductInstance(\Magento\Catalog\Model\Product $product) { $onlineCategory = $product->getData('online_category'); if (empty($onlineCategory)) { return null; } preg_match('/^.+\\((\\d+)\\)$/x', $onlineCategory, $matches); if (empty($matches[1])) { return null; } return $matches[1]; }
/** * Retrieve gallery entry ID that corresponds to the given file path * * @param Product $product * @param string $filePath * @return int|null */ public function getEntryIdByFilePath(Product $product, $filePath) { $mediaGalleryData = $product->getData('media_gallery'); if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) { return null; } foreach ($mediaGalleryData['images'] as $image) { if (isset($image['file']) && $image['file'] == $filePath) { return isset($image['value_id']) ? $image['value_id'] : null; } } return null; }
/** * Get configurations from product * * @param \Magento\Catalog\Model\Product $configurableProduct * @return array */ private function getConfigurationsFromProduct(\Magento\Catalog\Model\Product $configurableProduct) { $result = []; $configurableMatrix = $configurableProduct->hasData('configurable-matrix') ? $configurableProduct->getData('configurable-matrix') : []; foreach ($configurableMatrix as $item) { if (!$item['newProduct']) { $result[$item['id']] = $this->mapData($item); if (isset($item['qty'])) { $result[$item['id']]['quantity_and_stock_status']['qty'] = $item['qty']; } } } return $result; }
/** * Prepare stock item data for save * * @param \Magento\Catalog\Model\Product $product * @return $this */ protected function saveStockItemData($product) { $stockItemData = $product->getStockData(); $stockItemData['product_id'] = $product->getId(); if (!isset($stockItemData['website_id'])) { $stockItemData['website_id'] = $this->stockConfiguration->getDefaultScopeId(); } $stockItemData['stock_id'] = $this->stockRegistry->getStock($stockItemData['website_id'])->getStockId(); foreach ($this->paramListToCheck as $dataKey => $configPath) { if (null !== $product->getData($configPath['item']) && null === $product->getData($configPath['config'])) { $stockItemData[$dataKey] = false; } } $originalQty = $product->getData('stock_data/original_inventory_qty'); if (strlen($originalQty) > 0) { $stockItemData['qty_correction'] = (isset($stockItemData['qty']) ? $stockItemData['qty'] : 0) - $originalQty; } // todo resolve issue with builder and identity field name $stockItem = $this->stockRegistry->getStockItem($stockItemData['product_id'], $stockItemData['website_id']); $stockItem->addData($stockItemData); $this->stockItemRepository->save($stockItem); return $this; }
/** * Loads the values from a product model * * @param \Magento\Catalog\Model\Product $productModel * @return void */ protected function _populateBuilderWithAttributes(\Magento\Catalog\Model\Product $productModel) { $attributes = array(); foreach ($this->productBuilder->getCustomAttributesCodes() as $attrCode) { $value = $productModel->getDataUsingMethod($attrCode); $value = $value ? $value : $productModel->getData($attrCode); if (null !== $value) { if ($attrCode != 'entity_id') { $attributes[$attrCode] = $value; } } } $this->productBuilder->populateWithArray($attributes); return; }
/** * Loads the values from a product model * * @param \Magento\Catalog\Model\Product $productModel * @return void */ protected function populateBuilderWithAttributes(\Magento\Catalog\Model\Product $productModel) { $attributes = array(); foreach ($productModel->getAttributes() as $attribute) { $attrCode = $attribute->getAttributeCode(); $value = $productModel->getDataUsingMethod($attrCode) ?: $productModel->getData($attrCode); if (null !== $value) { if ($attrCode != 'entity_id') { $attributes[$attrCode] = $value; } } } $attributes[ProductDataObject::STORE_ID] = $productModel->getStoreId(); $this->productBuilder->populateWithArray($attributes); return; }
/** * 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'); } }