/** * Set current attribute to entry (for specified product) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Framework\Gdata\Gshopping\Entry $entry * @return \Magento\Framework\Gdata\Gshopping\Entry */ public function convertAttribute($product, $entry) { $url = $product->getProductUrl(false); if ($url) { $isStoreInUrl = $this->_scopeConfig->isSetFlag(\Magento\Store\Model\Store::XML_PATH_STORE_IN_URL, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if (!$isStoreInUrl) { $urlInfo = parse_url($url); $store = $product->getStore()->getCode(); if (isset($urlInfo['query']) && $urlInfo['query'] != '') { $url .= '&___store=' . $store; } else { $url .= '?___store=' . $store; } } $links = $entry->getLink(); if (!is_array($links)) { $links = []; } $link = $entry->getService()->newLink(); $link->setHref($url); $link->setRel('alternate'); $link->setType('text/html'); if ($product->getName()) { $link->setTitle($product->getName()); } $links[0] = $link; $entry->setLink($links); } return $entry; }
/** * @return array */ protected function prepareProducts($price) { $this->product->load(1); $productSecond = clone $this->product; $productSecond->setId(null)->setUrlKey(null)->setSku(uniqid($this->product->getSku() . '-'))->setName(uniqid($this->product->getName() . '-'))->setWebsiteIds([1]); $productSecond->save(); $productSecond->setPrice($price)->save(); $productThird = clone $this->product; $productThird->setId(null)->setUrlKey(null)->setSku(uniqid($this->product->getSku() . '-'))->setName(uniqid($this->product->getName() . '-'))->setWebsiteIds([1])->save(); $productThird->setPrice($price)->save(); return [$productSecond->getId(), $productThird->getId()]; }
/** * @magentoDbIsolation enabled * @magentoAppIsolation enabled * @magentoConfigFixture current_store catalog/frontend/flat_catalog_product 1 * @magentoDataFixture Magento/Catalog/_files/product_simple.php */ public function testProductsUpdate() { $this->_product->load(1); $this->_processor->reindexList([$this->_product->getId()]); $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Model\\CategoryFactory'); $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Block\\Product\\ListProduct'); $category = $categoryFactory->create()->load(2); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $this->assertCount(1, $productCollection); /** @var $product \Magento\Catalog\Model\Product */ foreach ($productCollection as $product) { $this->assertEquals($this->_product->getName(), $product->getName()); $this->assertEquals($this->_product->getShortDescription(), $product->getShortDescription()); } }
/** * 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; }
/** * Return image label * * @return string */ public function getLabel() { $label = $this->_product->getData($this->getType() . '_' . 'label'); if (empty($label)) { $label = $this->_product->getName(); } return $label; }
/** * {@inheritdoc} */ public function getName() { $pluginInfo = $this->pluginList->getNext($this->subjectType, 'getName'); if (!$pluginInfo) { return parent::getName(); } else { return $this->___callPlugins('getName', func_get_args(), $pluginInfo); } }
/** * @param \Magento\Catalog\Model\Product $product */ private function assertProductInfo($product) { $data = [1 => ['sku' => 'simple', 'name' => 'Simple Product', 'price' => '10', 'qty' => '1', 'position' => '1'], 21 => ['sku' => 'virtual-product', 'name' => 'Virtual Product', 'price' => '10', 'qty' => '2', 'position' => '2']]; $productId = $product->getId(); $this->assertEquals($data[$productId]['sku'], $product->getSku()); $this->assertEquals($data[$productId]['name'], $product->getName()); $this->assertEquals($data[$productId]['price'], $product->getPrice()); $this->assertEquals($data[$productId]['qty'], $product->getQty()); $this->assertEquals($data[$productId]['position'], $product->getPosition()); }
public function testGetName() { $this->assertEmpty($this->_model->getName()); $this->_model->setName('test'); $this->assertEquals('test', $this->_model->getName()); }
/** * Get title price for selection product * * @param \Magento\Catalog\Model\Product $selection * @param bool $includeContainer * @return string */ public function getSelectionTitlePrice($selection, $includeContainer = true) { $priceTitle = '<span class="product-name">' . $this->escapeHtml($selection->getName()) . '</span>'; $priceTitle .= ' ' . ($includeContainer ? '<span class="price-notice">' : '') . '+' . $this->renderPriceString($selection, $includeContainer) . ($includeContainer ? '</span>' : ''); return $priceTitle; }
/** * Add product data to stock item * * @param Product $product * @return $this */ public function setProduct(Product $product) { $this->setProductId($product->getId())->setStoreId($product->getStoreId())->setProductTypeId($product->getTypeId())->setProductName($product->getName())->setProductStatusChanged($product->dataHasChangedFor('status'))->setProductChangedWebsites($product->getIsChangedWebsites()); return $this; }
/** * Prepare url key for product * * @param \Magento\Catalog\Model\Product $product * @return string */ protected function prepareProductUrlKey(\Magento\Catalog\Model\Product $product) { $urlKey = $product->getUrlKey(); return $product->formatUrlKey($urlKey === '' || $urlKey === null ? $product->getName() : $urlKey); }
public function getObject(Product $product) { $type = $product->getTypeId(); $this->logger->start('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->getStoreId())); $defaultData = []; $transport = new DataObject($defaultData); $this->eventManager->dispatch('algolia_product_index_before', ['product' => $product, 'custom_data' => $transport]); $defaultData = $transport->getData(); $visibility = (int) $product->getVisibility(); $visibleInCatalog = $this->visibility->getVisibleInCatalogIds(); $visibleInSearch = $this->visibility->getVisibleInSearchIds(); $customData = ['objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl(false), 'visibility_search' => (int) in_array($visibility, $visibleInSearch), 'visibility_catalog' => (int) in_array($visibility, $visibleInCatalog)]; $additionalAttributes = $this->getAdditionalAttributes($product->getStoreId()); $groups = null; if ($this->isAttributeEnabled($additionalAttributes, 'description')) { $customData['description'] = $product->getDescription(); } $categories = []; $categories_with_path = []; $_categoryIds = $product->getCategoryIds(); if (is_array($_categoryIds) && count($_categoryIds) > 0) { $categoryCollection = $this->getAllCategories($_categoryIds); $rootCat = $this->storeManager->getStore($product->getStoreId())->getRootCategoryId(); foreach ($categoryCollection as $category) { // Check and skip all categories that is not // in the path of the current store. $path = $category->getPath(); $path_parts = explode('/', $path); if (isset($path_parts[1]) && $path_parts[1] != $rootCat) { continue; } $categoryName = $category->getName(); if ($categoryName) { $categories[] = $categoryName; } $category->getUrlInstance()->setStore($product->getStoreId()); $path = []; foreach ($category->getPathIds() as $treeCategoryId) { $name = $this->getCategoryName($treeCategoryId, $product->getStoreId()); if ($name) { $path[] = $name; } } $categories_with_path[] = $path; } } foreach ($categories_with_path as $result) { for ($i = count($result) - 1; $i > 0; $i--) { $categories_with_path[] = array_slice($result, 0, $i); } } $categories_with_path = array_intersect_key($categories_with_path, array_unique(array_map('serialize', $categories_with_path))); $categories_hierarchical = []; $level_name = 'level'; foreach ($categories_with_path as $category) { for ($i = 0; $i < count($category); $i++) { if (isset($categories_hierarchical[$level_name . $i]) === false) { $categories_hierarchical[$level_name . $i] = []; } $categories_hierarchical[$level_name . $i][] = implode(' /// ', array_slice($category, 0, $i + 1)); } } foreach ($categories_hierarchical as &$level) { $level = array_values(array_unique($level)); } foreach ($categories_with_path as &$category) { $category = implode(' /// ', $category); } $customData['categories'] = $categories_hierarchical; $customData['categories_without_path'] = $categories; /** @var Image $imageHelper */ $imageHelper = $this->objectManager->create('Algolia\\AlgoliaSearch\\Helper\\Image'); if (false === isset($defaultData['thumbnail_url'])) { $thumb = $imageHelper->init($product, 'thumbnail')->resize(75, 75); $customData['thumbnail_url'] = $thumb->getUrl(); } if (false === isset($defaultData['image_url'])) { $image = $imageHelper->init($product, $this->config->getImageType())->resize($this->config->getImageWidth(), $this->config->getImageHeight()); $customData['image_url'] = $image->getUrl(); if ($this->isAttributeEnabled($additionalAttributes, 'media_gallery')) { $product->load('media_gallery'); $customData['media_gallery'] = []; $images = $product->getMediaGalleryImages(); if ($images) { foreach ($images as $image) { $customData['media_gallery'][] = str_replace(['https://', 'http://'], '//', $image->getUrl()); } } } } $sub_products = []; $ids = null; if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') { if ($type == 'bundle') { $ids = []; $selection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product); foreach ($selection as $option) { $ids[] = $option->getProductId(); } } if ($type == 'configurable' || $type == 'grouped') { $ids = $product->getTypeInstance(true)->getChildrenIds($product->getId()); $ids = call_user_func_array('array_merge', $ids); } if (count($ids)) { $sub_products = $this->getProductCollectionQuery($product->getStoreId(), $ids, false)->load(); } } if (false === isset($defaultData['in_stock'])) { $stockItem = $this->stockRegistry->getStockItem($product->getId()); $customData['in_stock'] = $stockItem && (int) $stockItem->getIsInStock(); } // skip default calculation if we have provided these attributes via the observer in $defaultData if (false === isset($defaultData['ordered_qty']) && $this->isAttributeEnabled($additionalAttributes, 'ordered_qty')) { $customData['ordered_qty'] = (int) $product->getOrderedQty(); } if (false === isset($defaultData['total_ordered']) && $this->isAttributeEnabled($additionalAttributes, 'total_ordered')) { $customData['total_ordered'] = (int) $product->getTotalOrdered(); } if (false === isset($defaultData['stock_qty']) && $this->isAttributeEnabled($additionalAttributes, 'stock_qty')) { $customData['stock_qty'] = (int) $product->getStockQty(); } if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) { $customData['rating_summary'] = (int) $product->getRatingSummary(); } foreach ($additionalAttributes as $attribute) { if (isset($customData[$attribute['attribute']])) { continue; } $value = $product->getData($attribute['attribute']); $attribute_resource = $product->getResource()->getAttribute($attribute['attribute']); if ($attribute_resource) { $attribute_resource = $attribute_resource->setStoreId($product->getStoreId()); if ($value === null) { /* Get values as array in children */ if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') { $values = []; $all_sub_products_out_of_stock = true; /** @var Product $sub_product */ foreach ($sub_products as $sub_product) { $isInStock = (int) $this->stockRegistry->getStockItem($sub_product->getId())->getIsInStock(); if ($isInStock == false && $this->config->indexOutOfStockOptions($product->getStoreId()) == false) { continue; } $all_sub_products_out_of_stock = false; $value = $sub_product->getData($attribute['attribute']); if ($value) { $value_text = $sub_product->getAttributeText($attribute['attribute']); if ($value_text) { if (is_array($value_text)) { foreach ($value_text as $value_text_elt) { $values[] = $value_text_elt; } } else { $values[] = $value_text; } } else { $values[] = $attribute_resource->getFrontend()->getValue($sub_product); } } } if (is_array($values) && count($values) > 0) { $customData[$attribute['attribute']] = array_values(array_unique($values)); } if ($customData['in_stock'] && $all_sub_products_out_of_stock) { // Set main product out of stock if all // sub-products is out of stock. $customData['in_stock'] = 0; } } } else { $value_text = null; if (!is_array($value)) { $value_text = $product->getAttributeText($attribute['attribute']); } if ($value_text) { $value = $value_text; } else { $attribute_resource = $attribute_resource->setStoreId($product->getStoreId()); $value = $attribute_resource->getFrontend()->getValue($product); } if ($value) { $customData[$attribute['attribute']] = $value; } } } } $this->handlePrice($product, $sub_products, $customData); $transport = new DataObject($customData); $this->eventManager->dispatch('algolia_subproducts_index', ['custom_data' => $transport, 'sub_products' => $sub_products]); $customData = $transport->getData(); $customData = array_merge($customData, $defaultData); $customData['type_id'] = $type; $this->castProductObject($customData); $this->logger->stop('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->getStoreId())); return $customData; }
/** * Import product recurring payment information * Returns false if it cannot be imported * * @param \Magento\Catalog\Model\Product $product * @return $this|false */ public function importProduct(\Magento\Catalog\Model\Product $product) { if ($product->getIsRecurring() && is_array($product->getRecurringPayment())) { // import recurring payment data $this->addData($product->getRecurringPayment()); // automatically set product name if there is no schedule description if (!$this->hasScheduleDescription()) { $this->setScheduleDescription($product->getName()); } // collect start datetime from the product options $options = $product->getCustomOption(self::PRODUCT_OPTIONS_KEY); if ($options) { $options = unserialize($options->getValue()); if (is_array($options)) { if (isset($options['start_datetime'])) { $startDatetime = new \Magento\Framework\Stdlib\DateTime\Date($options['start_datetime'], \Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT); $this->setNearestStartDatetime($startDatetime); } } } return $this->_filterValues(); } return false; }
/** * set product * * @return $this */ public function setProduct(\Magento\Catalog\Model\Product $product) { $this->setProductName($product->getName()); $this->setProductSku($product->getSku()); return $this; }
/** * Generate product url key path * * @param \Magento\Catalog\Model\Product $product * @return string */ public function generateProductUrlKeyPath($product) { $urlKey = $product->getUrlKey() == '' ? $product->formatUrlKey($product->getName()) : $product->formatUrlKey($product->getUrlKey()); return $urlKey; }
/** * Render product item with options * * @param Product $product * @param array $options * @return string */ protected function _renderItemOptions(Product $product, array $options) { $html = '<div class="bundle-product-options">' . '<strong>' . $this->escapeHtml($product->getName()) . '</strong>' . '<dl>'; foreach ($options as $option) { $formattedOption = $this->getFormattedOptionValue($option); $html .= '<dt>' . $this->escapeHtml($option['label']) . '</dt>'; $html .= '<dd>' . $formattedOption['value'] . '</dd>'; } $html .= '</dl></div>'; return $html; }
/** * Parse \Exception Response Body * * @param string $message \Exception message to parse * @param null|\Magento\Catalog\Model\Product $product * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function parseGdataExceptionMessage($message, $product = null) { $result = []; foreach (explode("\n", $message) as $row) { if (trim($row) == '') { continue; } if (strip_tags($row) == $row) { $row = preg_replace('/@ (.*)/', __('See \'\\1\''), $row); if ($product !== null) { $row .= ' ' . __("for product '%1' (in '%2' store)", $product->getName(), $this->_storeManager->getStore($product->getStoreId())->getName()); } $result[] = $row; continue; } // parse not well-formatted xml preg_match_all('/(reason|field|type)=\\"([^\\"]+)\\"/', $row, $matches); if (is_array($matches) && count($matches) == 3 && is_array($matches[1]) && count($matches[1]) > 0) { $c = count($matches[1]); for ($i = 0; $i < $c; $i++) { if (isset($matches[2][$i])) { $result[] = ucfirst($matches[1][$i]) . ': ' . $matches[2][$i]; } } } } return implode(". ", $result); }
/** * Set current attribute to entry (for specified product) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Framework\Gdata\Gshopping\Entry $entry * @return \Magento\Framework\Gdata\Gshopping\Entry * @throws \Magento\Framework\Exception\LocalizedException */ public function convertAttribute($product, $entry) { $entry->cleanTaxes(); if ($this->_taxData->getConfig()->priceIncludesTax()) { return $entry; } $defaultCustomerTaxClassId = $this->_getDefaultCustomerTaxClassId($product->getStoreId()); $rates = $this->_taxRateManagement->getRatesByCustomerAndProductTaxClassId($defaultCustomerTaxClassId, $product->getTaxClassId()); $targetCountry = $this->_config->getTargetCountry($product->getStoreId()); $ratesTotal = 0; foreach ($rates as $rate) { $countryId = $rate->getTaxCountryId(); $postcode = $rate->getTaxPostcode(); if ($targetCountry == $countryId) { $regions = $this->_getRegionsByRegionId($rate->getTaxRegionId(), $postcode); $ratesTotal += count($regions); if ($ratesTotal > self::RATES_MAX) { throw new \Magento\Framework\Exception\LocalizedException(__('Google shopping only supports %1 tax rates per product', self::RATES_MAX)); } foreach ($regions as $region) { $adjustments = $product->getPriceInfo()->getAdjustments(); if (array_key_exists('tax', $adjustments)) { $taxIncluded = true; } else { $taxIncluded = false; } $quoteDetailsItemDataArray = ['code' => $product->getSku(), 'type' => 'product', 'tax_class_key' => [TaxClassKeyInterface::KEY_TYPE => TaxClassKeyInterface::TYPE_ID, TaxClassKeyInterface::KEY_VALUE => $product->getTaxClassId()], 'unit_price' => $product->getPrice(), 'quantity' => 1, 'tax_included' => $taxIncluded, 'short_description' => $product->getName()]; $billingAddressDataArray = ['country_id' => $countryId, 'region' => ['region_id' => $rate->getTaxRegionId()], 'postcode' => $postcode]; $shippingAddressDataArray = ['country_id' => $countryId, 'region' => ['region_id' => $rate->getTaxRegionId()], 'postcode' => $postcode]; $quoteDetailsDataArray = ['billing_address' => $billingAddressDataArray, 'shipping_address' => $shippingAddressDataArray, 'customer_tax_class_key' => [TaxClassKeyInterface::KEY_TYPE => TaxClassKeyInterface::TYPE_ID, TaxClassKeyInterface::KEY_VALUE => $defaultCustomerTaxClassId], 'items' => [$quoteDetailsItemDataArray]]; $quoteDetailsObject = $this->_quoteDetailsFactory->create(); $this->dataObjectHelper->populateWithArray($quoteDetailsObject, $quoteDetailsDataArray, '\\Magento\\Tax\\Api\\Data\\QuoteDetailsInterface'); $taxDetails = $this->_taxCalculationService->calculateTax($quoteDetailsObject, $product->getStoreId()); $taxRate = $taxDetails->getTaxAmount() / $taxDetails->getSubtotal() * 100; $entry->addTax(['tax_rate' => $taxRate, 'tax_country' => $countryId, 'tax_region' => $region]); } } } return $entry; }
/** * Generate product url key based on url_key entered by merchant or product name * * @param \Magento\Catalog\Model\Product $product * @return string */ public function generateUrlKey($product) { $urlKey = $product->getUrlKey(); return $product->formatUrlKey($urlKey === '' || $urlKey === null ? $product->getName() : $urlKey); }