/** * Retrieve product attributes as xml object * * @param Mage_Catalog_Model_Product $product * @param string $itemNodeName * @return Mage_XmlConnect_Model_Simplexml_Element */ public function productToXmlObject(Mage_Catalog_Model_Product $product, $itemNodeName = 'item') { /** @var $item Mage_XmlConnect_Model_Simplexml_Element */ $item = Mage::getModel('xmlconnect/simplexml_element', '<' . $itemNodeName . '></' . $itemNodeName . '>'); if ($product && $product->getId()) { $item->addChild('entity_id', $product->getId()); $item->addChild('name', $item->escapeXml($product->getName())); $item->addChild('entity_type', $product->getTypeId()); $item->addChild('short_description', $item->escapeXml($product->getShortDescription())); $description = Mage::helper('xmlconnect')->htmlize($item->xmlentities($product->getDescription())); $item->addChild('description', $description); $item->addChild('link', $product->getProductUrl()); if ($itemNodeName == 'item') { $imageToResize = Mage::helper('xmlconnect/image')->getImageSizeForContent('product_small'); $propertyToResizeName = 'small_image'; } else { $imageToResize = Mage::helper('xmlconnect/image')->getImageSizeForContent('product_big'); $propertyToResizeName = 'image'; } $icon = clone Mage::helper('catalog/image')->init($product, $propertyToResizeName)->resize($imageToResize); $iconXml = $item->addChild('icon', $icon); $file = Mage::helper('xmlconnect')->urlToPath($icon); $iconXml->addAttribute('modification_time', filemtime($file)); $item->addChild('in_stock', (int) $product->getIsInStock()); $item->addChild('is_salable', (int) $product->isSalable()); /** * By default all products has gallery (because of collection not load gallery attribute) */ $hasGallery = 1; if ($product->getMediaGalleryImages()) { $hasGallery = sizeof($product->getMediaGalleryImages()) > 0 ? 1 : 0; } $item->addChild('has_gallery', $hasGallery); /** * If product type is grouped than it has options as its grouped items */ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE || $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) { $product->setHasOptions(true); } $item->addChild('has_options', (int) $product->getHasOptions()); if ($minSaleQty = $this->_getMinimalQty($product)) { $item->addChild('min_sale_qty', (int) $minSaleQty); } if (!$product->getRatingSummary()) { Mage::getModel('review/review')->getEntitySummary($product, Mage::app()->getStore()->getId()); } $item->addChild('rating_summary', round((int) $product->getRatingSummary()->getRatingSummary() / 10)); $item->addChild('reviews_count', $product->getRatingSummary()->getReviewsCount()); if ($this->getChild('product_price')) { $this->getChild('product_price')->setProduct($product)->setProductXmlObj($item)->collectProductPrices(); } if ($this->getChild('additional_info')) { $this->getChild('additional_info')->addAdditionalData($product, $item); } } return $item; }
public function getProductDescription() { $_helper = Mage::helper('catalog/output'); $this->item['short_description'] = $_helper->productAttribute($this->product, nl2br($this->product->getShortDescription()), 'short_description'); $this->item['short_description'] = preg_replace('/(<img[^<>]+?src\\s*=\\s*\\")([^:\\"]+\\")/i', '$1' . Mage::getBaseUrl() . '$2', $this->item['short_description']); $this->item['detail_description'] = $_helper->productAttribute($this->product, $this->product->getDescription(), 'description'); if (preg_match('/{{(.+)}}/i', $this->item['detail_description'])) { $this->item['detail_description'] = preg_replace('/(\\<img[^<>]+src\\s*=\\s*"){{(\\w+)\\s*url="(.+)}}/i', '$1' . Mage::getBaseUrl() . '/$2/$3', $this->item['detail_description']); } $this->item['detail_description'] = preg_replace('/(<img[^<>]+?src\\s*=\\s*\\")([^:\\"]+\\")/i', '$1' . Mage::getBaseUrl() . '$2', $this->item['detail_description']); $this->item['specifications'] = $this->getProductFeature(); }
/** * Create Product array from Mage_Catalog_Model_Product * * @param Mage_Catalog_Model_Product $product * @return array */ public function getProductData(Mage_Catalog_Model_Product $product) { try { $data = array('url' => $product->getProductUrl(), 'title' => htmlspecialchars($product->getName()), 'spider' => 1, 'price' => $product->getPrice(), 'description' => urlencode($product->getDescription()), 'tags' => htmlspecialchars($product->getMetaKeyword()), 'images' => array(), 'vars' => array('sku' => $product->getSku(), 'storeId' => '', 'typeId' => $product->getTypeId(), 'status' => $product->getStatus(), 'categoryId' => $product->getCategoryId(), 'categoryIds' => $product->getCategoryIds(), 'websiteIds' => $product->getWebsiteIds(), 'storeIds' => $product->getStoreIds(), 'groupPrice' => $product->getGroupPrice(), 'formatedPrice' => $product->getFormatedPrice(), 'calculatedFinalPrice' => $product->getCalculatedFinalPrice(), 'minimalPrice' => $product->getMinimalPrice(), 'specialPrice' => $product->getSpecialPrice(), 'specialFromDate' => $product->getSpecialFromDate(), 'specialToDate' => $product->getSpecialToDate(), 'relatedProductIds' => $product->getRelatedProductIds(), 'upSellProductIds' => $product->getUpSellProductIds(), 'getCrossSellProductIds' => $product->getCrossSellProductIds(), 'isSuperGroup' => $product->isSuperGroup(), 'isGrouped' => $product->isGrouped(), 'isConfigurable' => $product->isConfigurable(), 'isSuper' => $product->isSuper(), 'isSalable' => $product->isSalable(), 'isAvailable' => $product->isAvailable(), 'isVirtual' => $product->isVirtual(), 'isRecurring' => $product->isRecurring(), 'isInStock' => $product->isInStock(), 'weight' => $product->getSku())); // Add product images if (self::validateProductImage($product->getImage())) { $data['images']['full'] = array("url" => $product->getImageUrl()); } if (self::validateProductImage($product->getSmallImage())) { $data['images']['smallImage'] = array("url" => $product->getSmallImageUrl($width = 88, $height = 77)); } if (self::validateProductImage($product->getThumbnail())) { $data['images']['thumb'] = array("url" => $product->getThumbnailUrl($width = 75, $height = 75)); } return $data; return $data; } catch (Exception $e) { Mage::logException($e); } }
public function getProductEntity(Mage_Catalog_Model_Product $product, $storeId, $includeExtras = true) { $result = array(); $result['entity_id'] = $product->getEntityId(); $result['sku'] = $product->getSku(); $result['name'] = $product->getName(); $result['price'] = $product->getPrice(); $result['special_price'] = $product->getSpecialPrice(); $result['special_from_date'] = $product->getSpecialFromDate(); $result['special_to_date'] = $product->getSpecialToDate(); $result['cost'] = $product->getCost(); $result['description'] = $product->getDescription(); $result['short_description'] = $product->getShortDescription(); $result['weight'] = $product->getWeight(); if ($product->isVisibleInSiteVisibility()) { $result['url_path'] = $this->_getProductUrlWithCache($product); } $parentProduct = $this->_getParentProduct($product); if ($parentProduct != null) { $result['parent_id'] = $parentProduct->getEntityId(); $result['parent_sku'] = $parentProduct->getSku(); if (!$product->isVisibleInSiteVisibility()) { $result['name'] = $parentProduct->getName(); if ($parentProduct->isVisibleInSiteVisibility()) { $result['url_path'] = $this->_getProductUrlWithCache($parentProduct); } } if ($includeExtras && Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE == $parentProduct->getTypeId()) { $result['purchasable'] = $this->_isPurchasable($product, $parentProduct); $attributes = $parentProduct->getTypeInstance(true)->getUsedProductAttributes($parentProduct); $freshProduct = null; foreach ($attributes as $attribute) { if (!array_key_exists('configurable_attributes', $result)) { $result['configurable_attributes'] = array(); } $attr = array(); $attr['attribute_name'] = $attribute->getFrontend()->getLabel(); $attr['value'] = $product->getAttributeText($attribute->getAttributeCode()); if (empty($attr['value'])) { // use the EAV tables only if the flat table doesn't work if ($freshProduct == null) { $freshProduct = Mage::getModel('catalog/product')->load($product->getEntityId()); } $attr['value'] = $attribute->getFrontend()->getValue($freshProduct); } $result['configurable_attributes'][] = $attr; } } } if (!isset($result['purchasable'])) { $result['purchasable'] = $this->_isPurchasable($product); } $images = $this->_getProductImages($product); if (isset($images['image'])) { $result['image'] = $images['image']; } if (isset($images['small_image'])) { $result['small_image'] = $images['small_image']; } if (isset($images['thumbnail'])) { $result['thumbnail'] = $images['thumbnail']; } if ($includeExtras) { // Metas $metas = $this->_getMetas($storeId, $product, $parentProduct); if ($metas != null) { //if(isset($metas['meta1'])) $result['meta1'] = $metas['meta1']; //if(isset($metas['meta2'])) $result['meta2'] = $metas['meta2']; //if(isset($metas['meta3'])) $result['meta3'] = $metas['meta3']; //if(isset($metas['meta4'])) $result['meta4'] = $metas['meta4']; if (isset($metas['meta5'])) { $result['meta5'] = $metas['meta5']; } } //Custom For ST Bernard Sports // Set IsNew Flag if product is less then 45 days old. $result['meta4'] = strtotime($product->getCreatedAt()) + 45 * 24 * 60 * 60 < time() ? "False" : "True"; // Brand and Category $brandAndCategoryProduct = !$parentProduct || $product->isVisibleInSiteVisibility() ? $product : $parentProduct; $setSettings = $this->_getProductAttributeSetSettings($brandAndCategoryProduct); if ($setSettings['brandAttribute'] != null) { $result['brand'] = $brandAndCategoryProduct->getAttributeText($setSettings['brandAttribute']); } if ($setSettings['catFromMagento']) { $cats = $this->_getCategoryInformation($storeId, $brandAndCategoryProduct); if (isset($cats['category'])) { $result['category'] = $cats['category']; } if (isset($cats['sub_category'])) { $result['sub_category'] = $cats['sub_category']; } //Custom For ST Bernard Sports if (isset($cats['third_category'])) { $result['meta3'] = $cats['third_category']; } } else { if ($setSettings['catFromAttributes']) { if ($setSettings['categoryAttribute'] != null) { $result['category'] = $brandAndCategoryProduct->getAttributeText($setSettings['categoryAttribute']); } if ($setSettings['subcategoryAttribute'] != null) { $result['sub_category'] = $brandAndCategoryProduct->getAttributeText($setSettings['subcategoryAttribute']); } } } // Inventory $result['in_stock'] = $product->isAvailable() ? "true" : "false"; $stockItem = $product->getStockItem(); if ($stockItem) { $result['qty_on_hand'] = $stockItem->getStockQty(); } // Related Products $result['links'] = $this->_getProductLinks($product); } $result['type'] = $product->getTypeId(); return $result; }
/** * Check Wishlist item has description * * @param Mage_Catalog_Model_Product $item * @return bool */ public function hasDescription($item) { return trim($item->getDescription()) != ''; }
/** * @param Mage_Catalog_Model_Product $product * * @return string */ protected function _getProductDescription($product) { $description = ""; $longDescription = $product->getDescription(); $shortDescription = $product->getShortDescription(); // Convert description and/or short description with nl2br $convertDescription = Mage::helper('shopgate')->getConfig()->getConvertDescription(true); if (in_array("0", $convertDescription)) { $longDescription = nl2br($longDescription); } else { if (in_array("1", $convertDescription)) { $shortDescription = nl2br($shortDescription); } } switch (Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_DESCRIPTION_TYPE)) { case 0: $description = $longDescription; break; case 1: $description = $shortDescription; break; case 2: $description = $longDescription; $description .= "<br /><br />"; $description .= $shortDescription; break; case 3: $description = $shortDescription; $description .= "<br /><br />"; $description .= $longDescription; break; case 4: $descriptionAttribute = Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DESCRIPTION_ATTR_CODE); $attributeCodes = explode(",", $descriptionAttribute); $counter = 0; foreach ($attributeCodes as $attributeCode) { $attributeCode = trim($attributeCode); if (!empty($attributeCode)) { /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute */ $attribute = $product->getResource()->getAttribute($attributeCode); $values = explode(',', $attribute->getFrontend()->getValue($product)); $description1 = implode('<br />', $values); if (in_array("2", $convertDescription)) { $description1 = nl2br($description1); } if (!empty($description1) && $counter > 0) { $description .= "<br /><br />"; } $description .= $description1; } $counter++; } } return $description; }
public function getObject(Mage_Catalog_Model_Product $product) { $type = $this->config->getMappedProductType($product->getTypeId()); $this->logger->start('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId)); $this->logger->log('Product type (' . $product->getTypeId() . ', mapped to: ' . $type . ')'); $defaultData = array(); $transport = new Varien_Object($defaultData); Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport)); $defaultData = $transport->getData(); $defaultData = is_array($defaultData) ? $defaultData : explode('|', $defaultData); $visibility = (int) $product->getVisibility(); /** @var Mage_Catalog_Model_Product_Visibility $catalogProductVisibility */ $catalogProductVisibility = Mage::getSingleton('catalog/product_visibility'); $visibleInCatalog = $catalogProductVisibility->getVisibleInCatalogIds(); $visibleInSearch = $catalogProductVisibility->getVisibleInSearchIds(); $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl(), 'visibility_search' => (int) in_array($visibility, $visibleInSearch), 'visibility_catalog' => (int) in_array($visibility, $visibleInCatalog)); $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId()); $groups = null; if ($this->isAttributeEnabled($additionalAttributes, 'description')) { $customData['description'] = $product->getDescription(); } $categories = array(); $categories_with_path = array(); $_categoryIds = $product->getCategoryIds(); if (is_array($_categoryIds) && count($_categoryIds) > 0) { $categoryCollection = Mage::getResourceModel('catalog/category_collection')->addAttributeToSelect('name')->addAttributeToFilter('entity_id', $_categoryIds)->addFieldToFilter('level', array('gt' => 1))->addIsActiveFilter(); if ($this->config->showCatsNotIncludedInNavigation($product->getStoreId()) == false) { $categoryCollection->addAttributeToFilter('include_in_menu', '1'); } $rootCat = Mage::app()->getStore($product->getStoreId())->getRootCategoryId(); /** @var Mage_Catalog_Model_Category $category */ 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 = array(); foreach ($category->getPathIds() as $treeCategoryId) { $name = $this->getCategoryName($treeCategoryId, $product->getStoreId()); if ($name) { $path[] = $name; } } $categories_with_path[] = $path; } } if ($this->config->indexWholeCategoryTree($product->getStoreId())) { 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 = array(); $mainCategories = array(); $level_name = 'level'; /** @var array $category */ foreach ($categories_with_path as $category) { $categoriesCount = count($category); for ($i = 0; $i < $categoriesCount; $i++) { if (isset($categories_hierarchical[$level_name . $i]) === false) { $categories_hierarchical[$level_name . $i] = array(); } $mainCategories[$level_name . $i][] = $category[$i]; if ($this->config->indexWholeCategoryTree($product->getStoreId())) { $categories_hierarchical[$level_name . $i][] = implode(' /// ', array_slice($category, 0, $i + 1)); } else { if ($i === $categoriesCount - 1) { $categories_hierarchical[$level_name . $i][] = implode(' /// ', $category); } } } } foreach ($categories_hierarchical as &$level) { $level = array_values(array_unique($level)); } foreach ($mainCategories 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; if ($this->isAttributeEnabled($additionalAttributes, 'main_categories')) { $customData['main_categories'] = $mainCategories; } /** @var Algolia_Algoliasearch_Helper_Image $imageHelper */ $imageHelper = Mage::helper('algoliasearch/image'); if (false === isset($defaultData['thumbnail_url'])) { /** @var Algolia_Algoliasearch_Helper_Image $thumb */ $thumb = $imageHelper->init($product, 'thumbnail')->resize(75, 75); try { $customData['thumbnail_url'] = $thumb->toString(); } catch (\Exception $e) { $this->logger->log($e->getMessage()); $this->logger->log($e->getTraceAsString()); $placeholderUrl = Mage::getDesign()->getSkinUrl($thumb->getPlaceholder()); $customData['thumbnail_url'] = $imageHelper->removeProtocol($placeholderUrl); } } if (false === isset($defaultData['image_url'])) { /** @var Algolia_Algoliasearch_Helper_Image $image */ $image = $imageHelper->init($product, $this->config->getImageType())->resize($this->config->getImageWidth(), $this->config->getImageHeight()); try { $customData['image_url'] = $image->toString(); } catch (\Exception $e) { $this->logger->log($e->getMessage()); $this->logger->log($e->getTraceAsString()); $placeholderUrl = Mage::getDesign()->getSkinUrl($image->getPlaceholder()); $customData['image_url'] = $imageHelper->removeProtocol($placeholderUrl); } if ($this->isAttributeEnabled($additionalAttributes, 'media_gallery')) { $product->load('media_gallery'); $customData['media_gallery'] = array(); foreach ($product->getMediaGalleryImages() as $image) { $customData['media_gallery'][] = $imageHelper->removeProtocol($image->getUrl()); } } } $sub_products = null; $ids = null; if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') { if ($type == 'bundle') { $ids = array(); $selection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product); foreach ($selection as $option) { $ids[] = $option->product_id; } } if ($type == 'configurable' || $type == 'grouped') { $ids = $product->getTypeInstance(true)->getChildrenIds($product->getId()); $ids = call_user_func_array('array_merge', $ids); } if (count($ids)) { $collection = $this->getProductCollectionQuery($product->getStoreId(), $ids, false); $sub_products = $collection->load(); } else { $sub_products = array(); } } if (false === isset($defaultData['in_stock'])) { $stockItem = $product->getStockItem(); $customData['in_stock'] = (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 (Mage::helper('core')->isModuleEnabled('Mage_Review')) { if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) { $customData['rating_summary'] = (int) $product->getRatingSummary(); } } $this->setNoAttributes($additionalAttributes); foreach ($additionalAttributes as $attribute) { $attribute_name = $attribute['attribute']; if (isset($customData[$attribute_name])) { continue; } $value = $product->getData($attribute_name); /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute_resource */ $attribute_resource = $product->getResource()->getAttribute($attribute_name); if ($attribute_resource) { $attribute_resource->setStoreId($product->getStoreId()); /** * if $value is missing or if the attribute is SKU, * use values from child products. */ if (($value === null || 'sku' == $attribute_name) && ($type == 'configurable' || $type == 'grouped' || $type == 'bundle')) { if ($value === null) { $values = array(); } else { $values = array($this->getValueOrValueText($product, $attribute_name, $attribute_resource)); } $all_sub_products_out_of_stock = true; if ($type !== 'bundle' || in_array($attribute_name, $this->excludedAttrsFromBundledProducts, true) === false) { foreach ($sub_products as $sub_product) { $isInStock = (int) $sub_product->getStockItem()->getIsInStock(); if ($isInStock == false && $this->config->indexOutOfStockOptions($product->getStoreId()) == false) { continue; } $all_sub_products_out_of_stock = false; $value = $sub_product->getData($attribute_name); if ($value) { $values[] = $this->getValueOrValueText($sub_product, $attribute_name, $attribute_resource); } } } if (is_array($values) && count($values) > 0) { $customData[$attribute_name] = array_values(array_unique($values, SORT_REGULAR)); } // Set main product out of stock if all // sub-products are out of stock. if ($customData['in_stock'] && $all_sub_products_out_of_stock) { $customData['in_stock'] = 0; } } elseif (!is_array($value)) { $value = $this->getValueOrValueText($product, $attribute_name, $attribute_resource); } if ($value && !isset($customData[$attribute_name])) { $customData[$attribute_name] = $value; } } } $msrpEnabled = method_exists(Mage::helper('catalog'), 'canApplyMsrp') ? (bool) Mage::helper('catalog')->canApplyMsrp($product) : false; if (false === $msrpEnabled) { $this->handlePrice($product, $sub_products, $customData); } else { unset($customData['price']); } $transport = new Varien_Object($customData); Mage::dispatchEvent('algolia_subproducts_index', array('custom_data' => $transport, 'sub_products' => $sub_products)); $customData = $transport->getData(); $customData = array_merge($customData, $defaultData); $customData['type_id'] = $type; $this->castProductObject($customData); $customData = $this->clearNoValues($customData); $this->logger->stop('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId)); return $customData; }
/** * Inflate an API object from a product object * * @param Mage_Catalog_Model_Product $product Product * @param int $storeId Magento store ID * @param bool $includeExtras Retrieve all information * * @return array */ public function getProductEntity(Mage_Catalog_Model_Product $product, $storeId, $includeExtras = true) { $result = array(); $result['entity_id'] = $product->getEntityId(); $result['sku'] = $product->getSku(); $result['name'] = $product->getName(); $result['price'] = $product->getPrice(); $result['special_price'] = $product->getSpecialPrice(); $result['special_from_date'] = $product->getSpecialFromDate(); $result['special_to_date'] = $product->getSpecialToDate(); $result['cost'] = $product->getCost(); $result['description'] = $product->getDescription(); $result['short_description'] = $product->getShortDescription(); $result['weight'] = $product->getWeight(); if ($product->isVisibleInSiteVisibility()) { $result['url_path'] = $this->_getProductUrlWithCache($product); } $parentProduct = $this->_getParentProduct($product); if ($parentProduct != null) { $result['parent_id'] = $parentProduct->getEntityId(); $result['parent_sku'] = $parentProduct->getSku(); if (!$product->isVisibleInSiteVisibility()) { $result['name'] = $parentProduct->getName(); if ($parentProduct->isVisibleInSiteVisibility()) { $result['url_path'] = $this->_getProductUrlWithCache($parentProduct); } } if ($includeExtras && $this->_isConfigurableProduct($parentProduct)) { $result['purchasable'] = $this->_isPurchasable($product, $parentProduct); /* @var Mage_Catalog_Model_Product_Type_Configurable $typeInst */ $typeInst = $parentProduct->getTypeInstance(true); $attributes = $typeInst->getUsedProductAttributes($parentProduct); /* @var Mage_Eav_Model_Entity_Attribute_Abstract $attribute */ foreach ($attributes as $attribute) { if (!array_key_exists('configurable_attributes', $result)) { $result['configurable_attributes'] = array(); } $result['configurable_attributes'][] = array('attribute_name' => $attribute->getAttributeCode()); } } } if (!isset($result['purchasable'])) { $result['purchasable'] = $this->_isPurchasable($product); } $images = $this->_getProductImages($product); if (isset($images['image'])) { $result['image'] = $images['image']; } if (isset($images['small_image'])) { $result['small_image'] = $images['small_image']; } if (isset($images['thumbnail'])) { $result['thumbnail'] = $images['thumbnail']; } if ($includeExtras) { $metas = $this->_getMetas($storeId, $product, $parentProduct); if ($metas != null) { /*if (isset($metas['meta3'])) { $result['meta3'] = $metas['meta3']; }*/ if (isset($metas['meta4'])) { $result['meta4'] = $metas['meta4']; } if (isset($metas['meta5'])) { $result['meta5'] = $metas['meta5']; } } //Custom for Sportys $stores = array(); foreach ($product->getStoreIds() as $storeID) { $store = Mage::getModel('core/store')->load($storeID); $stores[] = $store->getCode(); } $result["meta3"] = implode(',', $stores); // Brand and Category $brandCatProduct = $product; if ($parentProduct && !$product->isVisibleInSiteVisibility()) { $brandCatProduct = $parentProduct; } $setSettings = $this->_getProductAttributeSetSettings($brandCatProduct); if ($setSettings['brandAttribute'] != null) { $result['brand'] = $this->_getProductAttribute($brandCatProduct, $setSettings['brandAttribute']); } if ($setSettings['catFromMagento']) { $cats = $this->_getCategoryInformation($storeId, $brandCatProduct); if (isset($cats['category'])) { $result['category'] = $cats['category']; } if (isset($cats['sub_category'])) { $result['sub_category'] = $cats['sub_category']; } } else { if ($setSettings['catFromAttributes']) { if ($setSettings['categoryAttribute'] != null) { $result['category'] = $this->_getProductAttribute($brandCatProduct, $setSettings['categoryAttribute']); } if ($setSettings['subcategoryAttribute'] != null) { $result['sub_category'] = $this->_getProductAttribute($brandCatProduct, $setSettings['subcategoryAttribute']); } } } $result['attributes'] = $this->_getProductAttributes($product); // Inventory $result['in_stock'] = $product->isAvailable() ? "true" : "false"; /* @var Mage_Cataloginventory_Model_Stock_Item $stockItem */ $stockItem = $product->getStockItem(); if ($stockItem) { $result['qty_on_hand'] = $stockItem->getStockQty(); } // Related Products $result['links'] = $this->_getProductLinks($product); } $result['type'] = $product->getTypeId(); return $result; }
public function getProductEntity(Mage_Catalog_Model_Product $product, $storeId, $includeExtras = true) { $result = array(); $result['entity_id'] = $product->getEntityId(); $result['sku'] = $product->getSku(); $result['name'] = $product->getName(); $result['price'] = $product->getPrice(); $result['special_price'] = $product->getSpecialPrice(); $result['special_from_date'] = $product->getSpecialFromDate(); $result['special_to_date'] = $product->getSpecialToDate(); $result['cost'] = $product->getCost(); $result['description'] = $product->getDescription(); $result['short_description'] = $product->getShortDescription(); $result['weight'] = $product->getWeight(); if ($product->isVisibleInSiteVisibility()) { $prodUrlStr = $product->getProductUrl(); $prodUrl = Mage::getSingleton('core/url')->parseUrl($prodUrlStr); $result['url_path'] = substr($prodUrl->getPath(), 1); } $parentProduct = $this->_getParentProduct($product); if ($parentProduct != null) { $result['parent_id'] = $parentProduct->getEntityId(); $result['parent_sku'] = $parentProduct->getSku(); if (!$product->isVisibleInSiteVisibility()) { $result['name'] = $parentProduct->getName(); if ($parentProduct->isVisibleInSiteVisibility()) { $prodUrlStr = $parentProduct->getProductUrl(); $prodUrl = Mage::getSingleton('core/url')->parseUrl($prodUrlStr); $result['url_path'] = substr($prodUrl->getPath(), 1); } } if ($includeExtras && Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE == $parentProduct->getTypeId()) { $result['purchasable'] = $this->_isPurchasable($product, $parentProduct); $attributes = $parentProduct->getTypeInstance(true)->getUsedProductAttributes($parentProduct); foreach ($attributes as $attribute) { if (!array_key_exists('configurable_attributes', $result)) { $result['configurable_attributes'] = array(); } $attr = array(); $attr['attribute_name'] = $attribute->getFrontend()->getLabel(); $attr['value'] = $product->getAttributeText($attribute->getAttributeCode()); $result['configurable_attributes'][] = $attr; } } } if (!isset($result['purchasable'])) { $result['purchasable'] = $this->_isPurchasable($product); } $images = $this->_getProductImages($product); if (isset($images['image'])) { $result['image'] = $images['image']; } if (isset($images['small_image'])) { $result['small_image'] = $images['small_image']; } if (isset($images['thumbnail'])) { $result['thumbnail'] = $images['thumbnail']; } if ($includeExtras) { // Metas $metas = $this->_getMetas($storeId, $product, $parentProduct); if ($metas != null) { //if(isset($metas['meta1'])) $result['meta1'] = $metas['meta1']; //if(isset($metas['meta2'])) $result['meta2'] = $metas['meta2']; if (isset($metas['meta3'])) { $result['meta3'] = $metas['meta3']; } if (isset($metas['meta4'])) { $result['meta4'] = $metas['meta4']; } if (isset($metas['meta5'])) { $result['meta5'] = $metas['meta5']; } } // Brand and Category $brandAndCategoryProduct = !$parentProduct || $product->isVisibleInSiteVisibility() ? $product : $parentProduct; $setSettings = $this->_getProductAttributeSetSettings($brandAndCategoryProduct); if ($setSettings['brandAttribute'] != null) { $result['brand'] = $brandAndCategoryProduct->getAttributeText($setSettings['brandAttribute']); } if ($setSettings['catFromMagento']) { $cats = $this->_getCategoryInformation($storeId, $brandAndCategoryProduct); if (isset($cats['category'])) { $result['category'] = $cats['category']; } if (isset($cats['sub_category'])) { $result['sub_category'] = $cats['sub_category']; } } else { if ($setSettings['catFromAttributes']) { if ($setSettings['categoryAttribute'] != null) { $result['category'] = $brandAndCategoryProduct->getAttributeText($setSettings['categoryAttribute']); } if ($setSettings['subcategoryAttribute'] != null) { $result['sub_category'] = $brandAndCategoryProduct->getAttributeText($setSettings['subcategoryAttribute']); } } } // Inventory $result['in_stock'] = $product->isAvailable() ? "true" : "false"; $stockItem = $product->getStockItem(); if ($stockItem) { $result['qty_on_hand'] = $stockItem->getStockQty(); } // Related Products $result['links'] = $this->_getProductLinks($product); } $result['type'] = $product->getTypeId(); return $result; }
public function getObject(Mage_Catalog_Model_Product $product) { $type = $this->config->getMappedProductType($product->getTypeId()); $this->logger->start('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId)); $this->logger->log('Product type (' . $product->getTypeId() . ', mapped to: ' . $type . ')'); $defaultData = array(); $transport = new Varien_Object($defaultData); Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport)); $defaultData = $transport->getData(); $defaultData = is_array($defaultData) ? $defaultData : explode("|", $defaultData); $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl()); $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId()); $groups = null; if ($this->isAttributeEnabled($additionalAttributes, 'description')) { $customData['description'] = $product->getDescription(); } $categories = array(); $categories_with_path = array(); $_categoryIds = $product->getCategoryIds(); if (is_array($_categoryIds) && count($_categoryIds) > 0) { $categoryCollection = Mage::getResourceModel('catalog/category_collection')->addAttributeToSelect('name')->addAttributeToFilter('entity_id', $_categoryIds)->addFieldToFilter('level', array('gt' => 1))->addIsActiveFilter(); foreach ($categoryCollection as $category) { $categoryName = $category->getName(); if ($categoryName) { $categories[] = $categoryName; } $category->getUrlInstance()->setStore($product->getStoreId()); $path = array(); 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 = array(); $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] = array(); } $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; if (false === isset($defaultData['thumbnail_url'])) { $thumb = Mage::helper('algoliasearch/image')->init($product, 'thumbnail')->resize(75, 75); try { $customData['thumbnail_url'] = $thumb->toString(); $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', $customData['thumbnail_url']); } catch (\Exception $e) { $this->logger->log($e->getMessage()); $this->logger->log($e->getTraceAsString()); $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', Mage::getDesign()->getSkinUrl($thumb->getPlaceholder())); } } if (false === isset($defaultData['image_url'])) { $image = Mage::helper('algoliasearch/image')->init($product, $this->config->getImageType())->resize($this->config->getImageWidth(), $this->config->getImageHeight()); try { $customData['image_url'] = $image->toString(); $customData['image_url'] = str_replace(array('https://', 'http://'), '//', $customData['image_url']); } catch (\Exception $e) { $this->logger->log($e->getMessage()); $this->logger->log($e->getTraceAsString()); $customData['image_url'] = str_replace(array('https://', 'http://'), '//', Mage::getDesign()->getSkinUrl($image->getPlaceholder())); } if ($this->isAttributeEnabled($additionalAttributes, 'media_gallery')) { $product->load('media_gallery'); $customData['media_gallery'] = array(); foreach ($product->getMediaGalleryImages() as $image) { $customData['media_gallery'][] = str_replace(array('https://', 'http://'), '//', $image->getUrl()); } } } $sub_products = null; $ids = null; if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') { if ($type == 'bundle') { $ids = array(); $selection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product); foreach ($selection as $option) { $ids[] = $option->product_id; } } if ($type == 'configurable' || $type == 'grouped') { $ids = $product->getTypeInstance(true)->getChildrenIds($product->getId()); } if (count($ids)) { $sub_products = $this->getProductCollectionQuery($product->getStoreId(), $ids, false)->load(); } else { $sub_products = array(); } } if (false === isset($defaultData['in_stock'])) { $stockItem = $product->getStockItem(); $customData['in_stock'] = (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['stock_qty']) && $this->isAttributeEnabled($additionalAttributes, 'stock_qty')) { $customData['stock_qty'] = (int) $product->getStockQty(); } if (Mage::helper('core')->isModuleEnabled('Mage_Review')) { 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_ressource = $product->getResource()->getAttribute($attribute['attribute']); if ($attribute_ressource) { $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId()); if ($value === null) { /** Get values as array in children */ if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') { $values = array(); foreach ($sub_products as $sub_product) { $stock = (int) $sub_product->getStockItem()->getIsInStock(); if ($stock == false) { continue; } $value = $sub_product->getData($attribute['attribute']); if ($value) { $value_text = $sub_product->getAttributeText($attribute['attribute']); if ($value_text) { $values[] = $value_text; } else { $values[] = $attribute_ressource->getFrontend()->getValue($sub_product); } } } if (is_array($values) && count($values) > 0) { $customData[$attribute['attribute']] = array_values(array_unique($values)); } } } else { $value_text = $product->getAttributeText($attribute['attribute']); if ($value_text) { $value = $value_text; } else { $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId()); $value = $attribute_ressource->getFrontend()->getValue($product); } if ($value) { $customData[$attribute['attribute']] = $value; } } } } $this->handlePrice($product, $sub_products, $customData); $transport = new Varien_Object($customData); Mage::dispatchEvent('algolia_subproducts_index', array('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->storeId)); return $customData; }
public function getObject(Mage_Catalog_Model_Product $product) { $defaultData = array(); $transport = new Varien_Object($defaultData); Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport)); $defaultData = $transport->getData(); $defaultData = is_array($defaultData) ? $defaultData : explode("|", $defaultData); $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl(), 'description' => $product->getDescription()); foreach (array('price', 'price_with_tax', 'special_price_from_date', 'special_price_to_date', 'special_price', 'special_price_with_tax', 'special_price_formated', 'special_price_with_tax_formated', 'price_formated', 'price_with_tax_formated') as $price) { $customData[$price] = array(); } $this->handlePrice($product, $customData); if ($this->config->isCustomerGroupsEnabled()) { foreach ($groups = Mage::getModel('customer/group')->getCollection() as $group) { $group_id = (int) $group->getData('customer_group_id'); $this->handlePrice($product, $customData, $group_id); } } $categories = array(); $categories_with_path = array(); foreach ($this->getProductActiveCategories($product, $product->getStoreId()) as $categoryId) { $category = Mage::getModel('catalog/category')->load($categoryId); $categoryName = $category->getName(); if ($categoryName) { $categories[] = $categoryName; } $category->getUrlInstance()->setStore($product->getStoreId()); $path = array(); 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 = array(); $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] = array(); } $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; //array_values($categories_with_path); $customData['categories_without_path'] = $categories; if (false === isset($defaultData['thumbnail_url'])) { try { $customData['thumbnail_url'] = $product->getThumbnailUrl(); $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', $customData['thumbnail_url']); } catch (\Exception $e) { } } if (false === isset($defaultData['image_url'])) { try { $customData['image_url'] = $product->getImageUrl(); $customData['image_url'] = str_replace(array('https://', 'http://'), '//', $customData['image_url']); } catch (\Exception $e) { } } $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId()); $sub_products = null; if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') { if ($product->getTypeId() == 'grouped') { $sub_products = $product->getTypeInstance(true)->getAssociatedProducts($product); } if ($product->getTypeId() == 'configurable') { $sub_products = $product->getTypeInstance(true)->getUsedProducts(null, $product); } $min = PHP_INT_MAX; $max = 0; $min_with_tax = PHP_INT_MAX; $max_with_tax = 0; foreach ($sub_products as $sub_product) { $sub_product = Mage::getModel('catalog/product')->load($sub_product->getId()); $price = $sub_product->getPrice(); $price_with_tax = Mage::helper('tax')->getPrice($sub_product, $price, true, null, null, null, null, false); $min = min($min, $price); $max = max($max, $price); $min_with_tax = min($min_with_tax, $price_with_tax); $max_with_tax = max($max_with_tax, $price_with_tax); } $customData['min_formated'] = Mage::helper('core')->formatPrice($min, false); $customData['max_formated'] = Mage::helper('core')->formatPrice($max, false); $customData['min_with_tax_formated'] = Mage::helper('core')->formatPrice($min_with_tax, false); $customData['max_with_tax_formated'] = Mage::helper('core')->formatPrice($max_with_tax, false); } if (false === isset($defaultData['in_stock'])) { $stockItem = $product->getStockItem(); $customData['in_stock'] = (int) $stockItem->getIsInStock(); } // skip default calculation if we have provided these attributes via the observer in $defaultData if (false === isset($defaultData['ordered_qty']) && false === isset($defaultData['stock_qty'])) { $ordered_qty = Mage::getResourceModel('reports/product_collection')->addOrderedQty()->addAttributeToFilter('sku', $product->getSku())->setOrder('ordered_qty', 'desc')->getFirstItem()->ordered_qty; $customData['ordered_qty'] = (int) $ordered_qty; $customData['stock_qty'] = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty(); if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') { $ordered_qty = 0; $stock_qty = 0; foreach ($sub_products as $sub_product) { $stock_qty += (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($sub_product)->getQty(); $ordered_qty += (int) $this->getReportForProduct($sub_product)->ordered_qty; } $customData['ordered_qty'] = $ordered_qty; $customData['stock_qty'] = $stock_qty; } if ($this->isAttributeEnabled($additionalAttributes, 'ordered_qty') == false) { unset($customData['ordered_qty']); } if ($this->isAttributeEnabled($additionalAttributes, 'stock_qty') == false) { unset($customData['stock_qty']); } } if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) { $summaryData = Mage::getModel('review/review_summary')->setStoreId($product->getStoreId())->load($product->getId()); if ($summaryData['rating_summary']) { $customData['rating_summary'] = $summaryData['rating_summary']; } } foreach ($additionalAttributes as $attribute) { if (isset($customData[$attribute['attribute']])) { continue; } $value = $product->getData($attribute['attribute']); $attribute_ressource = $product->getResource()->getAttribute($attribute['attribute']); if ($attribute_ressource) { $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId()); if ($value === null) { /** Get values as array in children */ if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') { $values = array(); foreach ($sub_products as $sub_product) { $sub_product = Mage::getModel('catalog/product')->load($sub_product->getId()); $value = $sub_product->getData($attribute['attribute']); if ($value) { $value_text = $sub_product->getAttributeText($attribute['attribute']); if ($value_text) { $values[] = $value_text; } else { $values[] = $attribute_ressource->getFrontend()->getValue($sub_product); } } } if (count($values) > 0) { $customData[$attribute['attribute']] = $values; } } } else { $value_text = $product->getAttributeText($attribute['attribute']); if ($value_text) { $value = $value_text; } else { $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId()); $value = $attribute_ressource->getFrontend()->getValue($product); } if ($value) { $customData[$attribute['attribute']] = $value; } } } } $customData = array_merge($customData, $defaultData); $customData['type_id'] = $product->getTypeId(); $this->castProductObject($customData); return $customData; }
/** * @param Mage_Catalog_Model_Product $product * * @return array */ public static function createFromProduct(Mage_Catalog_Model_Product $product) { $article = array('id' => $product->getId(), 'name' => $product->getName(), 'description' => substr($product->getDescription(), 0, 255), 'url' => $product->getProductUrl(), 'image_url' => $product->getImageUrl()); return $article; }