/** * @param Mage_Catalog_Model_Resource_Product_Collection $products * @return bool */ protected function _process($products) { $processor = $this->_htmlProcessor; $helper = $this->_getHelper(); foreach ($products as $product) { $product->setData('url', $product->getProductUrl()); } $items = $processor->query($helper->getCssSelector('related_product_link')); if (count($items) === 0) { return false; } $positions = array(); foreach ($items as $i => $item) { /** @var $item DOMElement */ $url = $item->getAttribute('href'); $product = $products->getItemByColumnValue('url', $url); if (!$product) { continue; } if ($helper->isEnabledForProduct($product)) { $positions[] = $i; } } $processor->replace($helper->getCssSelector('related_product_price'), $this->_getHelper()->prepareReplacement(), $positions); }
/** * Callback method for applying price filter. * @param Mage_Catalog_Model_Resource_Product_Collection $_collection * @param Mage_Adminhtml_Block_Widget_Grid_Column $_column */ public function _filterPrice($_collection, $_column) { $_field = $_column->getFilterIndex() ? $_column->getFilterIndex() : $_column->getIndex(); $_condition = $_column->getFilter()->getCondition(); if (!$_field || !is_array($_condition)) { return; } if (!array_key_exists('type', $_condition) || !is_numeric($_condition['type'])) { $_collection->addFieldToFilter($_field, $_condition); } else { $_storeId = (int) $this->getRequest()->getParam('store', 0); $_store = Mage::app()->getStore($_storeId); $_joinCondition = array('`e`.`entity_id` = `at_reservation_price`.`entity_id`', '`at_reservation_price`.`store_id` = ' . $_store->getId(), '`at_reservation_price`.`ptype` = ' . $_condition['type']); if (array_key_exists('from', $_condition)) { $_joinCondition[] = '`at_reservation_price`.`price` >= ' . $_condition['from']; } if (array_key_exists('to', $_condition)) { $_joinCondition[] = '`at_reservation_price`.`price` <= ' . $_condition['to']; } $_joinCondition[] = '`at_reservation_price`.`date_from` = \'0000-00-00 00:00:00\' OR DATE(`at_reservation_price`.`date_from`) <= DATE(\'' . date('Y-m-d H:i:s', Mage::getModel('core/date')->gmtTimestamp(time())) . '\')'; $_joinCondition[] = '`at_reservation_price`.`date_to` = \'0000-00-00 00:00:00\' OR DATE(`at_reservation_price`.`date_to`) >= DATE(\'' . date('Y-m-d H:i:s', Mage::getModel('core/date')->gmtTimestamp(time())) . '\')'; $_collection->getSelect()->joinInner(array('at_reservation_price' => $_collection->getTable('payperrentals/reservationprices')), '(' . implode(') AND (', $_joinCondition) . ')', array('price_type' => 'at_reservation_price.ptype', 'reservation_price' => 'at_reservation_price.price', 'reservation_number' => 'at_reservation_price.numberof')); /** TODO Check collection count calculation with group. I think need change join for use distinct */ $_collection->getSelect()->group('e.entity_id'); } }
/** * Add only is in stock products filter to product collection * * @param Mage_Catalog_Model_Resource_Product_Collection $collection * * @return Mage_CatalogInventory_Model_Resource_Stock_Status */ public function addIsInStockFilterToCollection($collection) { $websiteId = Mage::app()->getStore($collection->getStoreId())->getWebsiteId(); $joinCondition = $this->_getReadAdapter()->quoteInto('e.entity_id = status_table_mli.product_id' . ' AND status_table_mli.store_id = ?', Mage::app()->getStore()->getId()); $collection->getSelect()->join(array('status_table_mli' => $this->getTable('demac_multilocationinventory/stock_status_index')), $joinCondition, array())->where('status_table_mli.is_in_stock=1'); return $this; }
/** * Make collection not to load products that are in specified quote * * @param Mage_Catalog_Model_Resource_Product_Collection $collection * @param int $quoteId * @return Mage_Checkout_Model_Resource_Cart */ public function addExcludeProductFilter($collection, $quoteId) { $adapter = $this->_getReadAdapter(); $exclusionSelect = $adapter->select()->from($this->getTable('sales/quote_item'), array('product_id'))->where('quote_id = ?', $quoteId); $condition = $adapter->prepareSqlCondition('e.entity_id', array('nin' => $exclusionSelect)); $collection->getSelect()->where($condition); return $this; }
/** * Add join for catalog in stock field to product collection * * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection * @return Mage_CatalogInventory_Model_Resource_Stock_Item */ public function addCatalogInventoryToProductCollection($productCollection) { $adapter = $this->_getReadAdapter(); $isManageStock = (int) Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK); $stockExpr = $adapter->getCheckSql('cisi.use_config_manage_stock = 1', $isManageStock, 'cisi.manage_stock'); $stockExpr = $adapter->getCheckSql("({$stockExpr} = 1)", 'cisi.is_in_stock', '1'); $productCollection->joinTable(array('cisi' => 'cataloginventory/stock_item'), 'product_id=entity_id', array('is_saleable' => new Zend_Db_Expr($stockExpr), 'inventory_in_stock' => 'is_in_stock'), null, 'left'); return $this; }
public function addMinimalPrices(Mage_Catalog_Model_Resource_Product_Collection $collection) { $minimalPrices = $this->_getResource()->getMinimalPrices($collection->getLoadedIds()); foreach ($minimalPrices as $row) { $item = $collection->getItemById($row['entity_id']); if ($item) { $item->setData('minimal_price', $row['value']); $item->setData('minimal_tax_class_id', $row['tax_class_id']); } } }
/** * @dataProvider setOrderDataProvider */ public function testSetOrder($order, $expectedOrder) { $this->_collection->setOrder($order); $this->_collection->load(); // perform real SQL query $selectOrder = $this->_collection->getSelect()->getPart(Zend_Db_Select::ORDER); foreach ($expectedOrder as $field) { $orderBy = array_shift($selectOrder); $this->assertArrayHasKey(0, $orderBy); $this->assertTrue(false !== strpos($orderBy[0], $field), 'Ordering by same column more than once is restricted by multiple RDBMS requirements.'); } }
/** * Added exception handling to addItem, otherwise in some cases will throw an exception * * @param \Varien_Object $object */ public function addItem(\Varien_Object $object) { try { return parent::addItem($object); } catch (Exception $e) { } }
/** * Add tax class id attribute to select and join price rules data if needed * * @return Mage_Catalog_Model_Resource_Product_Collection */ protected function _beforeLoad() { if (isset($this->_productLimitationFilters['category_id']) && is_array($this->_productLimitationFilters['category_id'])) { $this->getSelect()->group('e.entity_id'); } return parent::_beforeLoad(); }
/** * @param Mage_Catalog_Model_Resource_Product_Collection $collection * @param string $currDir * * @return $this */ public function apply($collection, $currDir) { if (!$this->isEnabled()) { return $this; } $alias = 'price_index'; if (preg_match('/`([a-z0-9\\_]+)`\\.`final_price`/', $collection->getSelect()->__toString(), $m)) { $alias = $m[1]; } $price = Mage::getStoreConfig('amsorting/general/profit_price'); $attribute = Mage::getStoreConfig('amsorting/general/product_attribute'); $collection->joinAttribute('cost', Mage_Catalog_Model_Product::ENTITY . '/' . $attribute, 'entity_id', null, 'left', Mage::app()->getStore()->getId()); $collection->getSelect()->columns(array('profit' => "(`{$alias}`.`{$price}` - IF(`at_cost`.`value` IS NULL, 0, `at_cost`.`value`))")); $collection->getSelect()->order("profit {$currDir}"); return $this; }
public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) { if ($attribute == 'best') { $this->getSelect()->order("t2.position " . $dir); return $this; } return parent::addAttributeToSort($attribute, $dir); }
/** * Add attribute to sort * * @param string $attribute * @param string $dir * @return Mage_Reports_Model_Resource_Review_Product_Collection */ public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC) { if (in_array($attribute, array('review_cnt', 'last_created', 'avg_rating', 'avg_rating_approved'))) { $this->getSelect()->order($attribute . ' ' . $dir); return $this; } return parent::addAttributeToSort($attribute, $dir); }
/** * @param Mage_Catalog_Model_Resource_Product_Collection $productCollection * @return mixed */ public function sort(Mage_Catalog_Model_Resource_Product_Collection $productCollection) { //Pass a small validation if (!$this->_getHelper()->isCategorySortingEnable() || $productCollection->getFlag(self::MARKETO_SORTED)) { return $productCollection; } $categoriesList = $this->_getPesonalizeCalculator()->getScoreCategoryParams(HooshMarketing_Marketo_Model_Personalize_Calculator::CATEGORY_ID_AND_SCORE); //get List of categories with key -> Category_id and value - Score if (!count($categoriesList)) { //if we havn`t score categories do nothing return $productCollection; } uasort($categoriesList, function ($f, $s) { return $f > $s ? 1 : -1; //sort by descending }); //Sort categories in order to show top scored categories first $categoriesList = array_keys($categoriesList); // get only category ids try { $productCategoryTable = $this->_getCoreResource()->getTableName("catalog_category_product"); $productCollection->getSelect()->joinLeft(array("marketo_category_table" => $productCategoryTable), "marketo_category_table.product_id = e.entity_id", array("top_category_id" => "marketo_category_table.category_id"))->group("entity_id")->order("FIELD(top_category_id, " . implode(',', $categoriesList) . ") DESC"); //order by top $productCollection->setFlag(self::MARKETO_SORTED, true); //to set order only one time } catch (Exception $e) { Mage::logException($e); } return $productCollection; }
/** * Set Order field * * @param string $attribute * @param string $dir * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection */ public function setOrder($attribute, $dir = 'desc') { if ($attribute == 'relevance') { //$this->getSelect()->order("relevance {$dir}"); } else { parent::setOrder($attribute, $dir); } return $this; }
/** * Apply filter by category id * * @param Mage_Catalog_Model_Resource_Product_Collection $collection */ protected function _applyCategoryFilter(Mage_Catalog_Model_Resource_Product_Collection $collection) { $categoryId = $this->getRequest()->getParam('category_id'); if ($categoryId) { $category = $this->_getCategoryById($categoryId); if (!$category->getId()) { $this->_critical('Category not found.', Mage_Api2_Model_Server::HTTP_BAD_REQUEST); } $collection->addCategoryFilter($category); } }
/** * @param Mage_Catalog_Model_Resource_Product_Collection $collection * @param string $currDir * * @return $this */ public function apply($collection, $currDir) { if (!$this->isEnabled()) { return $this; } $sorters = $this->getSorters(); if (Mage::getStoreConfig('amsorting/general/use_index')) { foreach ($sorters as $sorter) { $collection->joinField($sorter->getCode(), $sorter->getIndexTable(), $sorter->getCode(), 'id=entity_id', array('store_id' => Mage::app()->getStore()->getId()), 'left'); } } else { $select = $collection->getSelect(); $col = $select->getPart('columns'); foreach ($sorters as $sorter) { $col[] = array('', $sorter->getColumnSelect(), $sorter->getCode()); } $select->setPart('columns', $col); } $collection->getSelect()->order(new Zend_Db_Expr('(' . $sorters['dividend']->getCode() . '/' . $sorters['divider']->getCode() . ') ' . $currDir)); return $this; }
public function load() { if ($this->_isLoaded) { return $this; } $this->_isLoaded = true; if (isset($this->_vrecId)) { $this->loadVrec(); } else { $this->loadFromQuery(); } return parent::load(); }
/** * Set Order field * * @param string $attribute * @param string $dir * @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection */ public function setOrder($attribute, $dir = 'desc') { if (!$this->checkSearchaniseResult()) { return parent::setOrder($attribute, $dir); } if ($attribute == 'relevance') { $product_ids = $this->getSearchaniseRequest()->getProductIdsString(); if (!empty($product_ids)) { $this->getSelect()->order("FIELD (e.entity_id, {$product_ids}) {$dir}"); } } else { parent::setOrder($attribute, $dir); } return $this; }
/** * Update product links for the given type of links - up sell, related, cross sell * @param Mage_Catalog_Model_Product $product Product to add links to * @param array $linkUpdates Product links data * @param string $linkType Type of product links to create * @return array Any links that could not be added */ protected function _linkProducts(Mage_Catalog_Model_Product $product, $linkUpdates, $linkType) { $opFilter = function ($operation) { return function ($el) use($operation) { return strtolower($el['operation_type']) === $operation; }; }; $skuMap = function ($link) { return $link['link_to_unique_id']; }; // get all currently linked products of this link type $linkedProductsGetter = $this->_linkTypes[$linkType]['linked_products_getter_method']; $linkedProducts = $product->{$linkedProductsGetter}(); // remove any links that are supposed to be getting deleted $deleteSkus = array_map($skuMap, array_filter($linkUpdates, $opFilter('delete'))); $linkedProducts = array_filter($linkedProducts, function ($prod) use($deleteSkus) { return !in_array($prod->getSku(), $deleteSkus); }); $addSkus = array_map($skuMap, array_filter($linkUpdates, $opFilter('add'))); // Go through the skus to add and look up the product id for each one. // If any are missing, add the product link for that sku to a list of links that // cannot be resolved yet. $missingLinks = array(); $idsToAdd = array(); foreach ($addSkus as $sku) { $linkProduct = $this->_products->getItemByColumnValue('sku', $sku); $id = $linkProduct ? $linkProduct->getId() : null; if ($id) { $idsToAdd[] = $id; } else { $missingLinks[] = $this->_buildProductLinkForSku($sku, $linkType, 'Add'); } } // get a list of all products that should be linked $linkIds = array_filter(array_unique(array_merge(array_map(function ($prod) { return $prod->getId(); }, $linkedProducts), $idsToAdd))); $linkData = array(); foreach ($linkIds as $id) { $linkData[$id] = array('position' => ''); } // add the updated links to the product $product->setData($this->_linkTypes[$linkType]['data_attribute'], $linkData); // return links that were not resolved return $missingLinks; }
/** * Get link collection * * @return Mage_Catalog_Model_Resource_Product_Collection|null */ public function getLinkCollection() { if (is_null($this->_linkCollection)) { $this->_linkCollection = $this->_getTargetLinkCollection(); if ($this->_linkCollection) { // Perform rotation mode $select = $this->_linkCollection->getSelect(); $rotationMode = $this->getTargetRuleHelper()->getRotationMode($this->getProductListType()); if ($rotationMode == Enterprise_TargetRule_Model_Rule::ROTATION_SHUFFLE) { Mage::getResourceSingleton('enterprise_targetrule/index')->orderRand($select); } else { $select->order('link_attribute_position_int.value ASC'); } } } return $this->_linkCollection; }
/** * Treat "order by" items as attributes to sort * * @return Mage_Tag_Model_Resource_Product_Collection */ protected function _renderOrders() { if (!$this->_isOrdersRendered) { parent::_renderOrders(); $orders = $this->getSelect()->getPart(Zend_Db_Select::ORDER); $appliedOrders = array(); foreach ($orders as $order) { $appliedOrders[$order[0]] = true; } foreach ($this->_orders as $field => $direction) { if (empty($appliedOrders[$field])) { $this->_select->order(new Zend_Db_Expr($field . ' ' . $direction)); } } } return $this; }
/** * Add all attributes and apply pricing logic to products collection * to get correct values in different products lists. * E.g. crosssells, upsells, new products, recently viewed * * @param Mage_Catalog_Model_Resource_Product_Collection $collection * @return Mage_Catalog_Model_Resource_Product_Collection */ protected function _addProductAttributesAndPrices(Mage_Catalog_Model_Resource_Product_Collection $collection) { $test = Mage::getSingleton('catalog/config')->getProductAttributes(); return $collection->addMinimalPrice()->addFinalPrice()->addTaxPercents()->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())->addUrlRewrite(); }
/** * Rewrite retrieve attribute field name for wishlist attributes * * @param string $attributeCode * @return Mage_Wishlist_Model_Resource_Product_Collection */ protected function _getAttributeFieldName($attributeCode) { if ($attributeCode == 'days_in_wishlist') { return $this->_joinFields[$attributeCode]['field']; } return parent::_getAttributeFieldName($attributeCode); }
/** * Redeclare parent method for store filters applying * * @return Mage_Review_Model_Resource_Review_Product_Collection */ protected function _beforeLoad() { parent::_beforeLoad(); $this->_applyStoresFilterToSelect(); return $this; }
/** * Add low stock filter to product collection * * @param Mage_Catalog_Model_Resource_Product_Collection $collection * @param array $fields * @return Mage_CatalogInventory_Model_Resource_Stock */ public function addLowStockFilter(Mage_Catalog_Model_Resource_Product_Collection $collection, $fields) { $this->_initConfig(); $adapter = $collection->getSelect()->getAdapter(); $qtyIf = $adapter->getCheckSql('invtr.use_config_notify_stock_qty', $this->_configNotifyStockQty, 'invtr.notify_stock_qty'); $conditions = array(array($adapter->prepareSqlCondition('invtr.use_config_manage_stock', 1), $adapter->prepareSqlCondition($this->_isConfigManageStock, 1), $adapter->prepareSqlCondition('invtr.qty', array('lt' => $qtyIf))), array($adapter->prepareSqlCondition('invtr.use_config_manage_stock', 0), $adapter->prepareSqlCondition('invtr.manage_stock', 1))); $where = array(); foreach ($conditions as $k => $part) { $where[$k] = join(' ' . Zend_Db_Select::SQL_AND . ' ', $part); } $where = $adapter->prepareSqlCondition('invtr.low_stock_date', array('notnull' => true)) . ' ' . Zend_Db_Select::SQL_AND . ' ((' . join(') ' . Zend_Db_Select::SQL_OR . ' (', $where) . '))'; $collection->joinTable(array('invtr' => 'cataloginventory/stock_item'), 'product_id = entity_id', $fields, $where); return $this; }
/** * Handles collection filtering by ids retrieves from search engine. * Will also stores faceted data and total records. * * @return Mage_Catalog_Model_Resource_Product_Collection */ protected function _beforeLoad() { $this->_prepareQuery(); $ids = array(); if (!empty($this->_facets)) { $this->getSearchEngineQuery()->resetFacets(); } $result = $this->getSearchEngineQuery()->search(); $ids = isset($result['ids']) ? $result['ids'] : array(); if (isset($result['facets'])) { $this->_facets = array_merge($this->_facets, $result['facets']); } $this->_totalRecords = isset($result['total_count']) ? $result['total_count'] : null; $this->_isSpellChecked = $this->getSearchEngineQuery()->isSpellchecked(); if (empty($ids)) { $ids = array(0); // Fix for no result } $this->addIdFilter($ids); $this->_searchedEntityIds = $ids; $this->_pageSize = false; return parent::_beforeLoad(); }
/** * Add filtering * * @param string $field * @param string $condition * @return Mage_Reports_Model_Resource_Product_Downloads_Collection */ public function addFieldToFilter($field, $condition = null) { if ($field == 'link_title') { $conditionSql = $this->_getConditionSql('l.title', $condition); $this->getSelect()->where($conditionSql); } else { parent::addFieldToFilter($field, $condition); } return $this; }
/** * Retrieve is flat enabled flag * Overwrite disable flat for compared item if required EAV resource * * @return bool */ public function isEnabledFlat() { if (!Mage::helper('catalog/product_compare')->getAllowUsedFlat()) { return false; } return parent::isEnabledFlat(); }
/** * Set order * * @param string $attribute * @param string $dir * @return Mage_Reports_Model_Resource_Product_Collection */ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC) { if (in_array($attribute, array('carts', 'orders', 'ordered_qty'))) { $this->getSelect()->order($attribute . ' ' . $dir); } else { parent::setOrder($attribute, $dir); } return $this; }
/** * Initialize collection select * */ protected function _initSelect() { parent::_initSelect(); $this->getSelect()->join(array('selection' => $this->_selectionTable), 'selection.product_id = e.entity_id', array('*')); }