Last active
July 29, 2016 20:35
-
-
Save crodrigues/f6af99eac3b2f3a0b1e3592567ef056b to your computer and use it in GitHub Desktop.
Extend functionality of Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToFilter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add attribute filter to collection (extended) | |
* | |
* If $attribute is an array with following format, each condition will be | |
* separated by an OR, unless specified with a third 'and' property set to true: | |
* | |
* array( | |
* array('attribute'=>'firstname', 'like'=>'test%'), | |
* array('attribute'=>'lastname', 'like'=>'test%'), | |
* ) | |
* | |
* or... | |
* | |
* array( | |
* array('attribute'=>'firstname', 'like'=>'test%'), | |
* array('attribute'=>'lastname', 'like'=>'test%', 'and' => true), | |
* ) | |
* | |
* @see self::_getConditionSql for $condition | |
* @param Mage_Eav_Model_Entity_Attribute_Interface|integer|string|array $attribute | |
* @param null|string|array $condition | |
* @param string $joinType | |
* @param bool $and 'AND' conjunction by default; 'OR' if false | |
* @return Mage_Eav_Model_Entity_Collection_Abstract | |
*/ | |
public function addAttributeToFilter($attribute, $condition = null, $joinType = 'inner', $and = true) | |
{ | |
if ($attribute === null) { | |
$this->getSelect(); | |
return $this; | |
} | |
if (is_numeric($attribute)) { | |
$attribute = $this->getEntity()->getAttribute($attribute)->getAttributeCode(); | |
} else if ($attribute instanceof Mage_Eav_Model_Entity_Attribute_Interface) { | |
$attribute = $attribute->getAttributeCode(); | |
} | |
if (is_array($attribute)) { | |
$sqlArr = array(); | |
foreach ($attribute as $k => $condition) { | |
$conjunction = $k . ':' . (empty($condition['and']) ? 'OR' : 'AND'); | |
$sqlArr[$conjunction] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType); | |
} | |
$conditionSql = '('; | |
foreach ($sqlArr as $conjunction => $arr) { | |
$conditionSql .= "{$arr}) " . explode(':', $conjunction)[1] . ' ('; | |
} | |
$conditionSql = preg_replace('/(?: (?:OR|AND) \()$/', '', $conditionSql, 1) . ')'; | |
} else if (is_string($attribute)) { | |
if ($condition === null) { | |
$condition = ''; | |
} | |
$conditionSql = $this->_getAttributeConditionSql($attribute, $condition, $joinType); | |
} | |
$method = $and ? 'where' : 'orWhere'; | |
if (!empty($conditionSql)) { | |
$this->getSelect()->{$method}($conditionSql, null, Varien_Db_Select::TYPE_CONDITION); | |
} else { | |
Mage::throwException('Invalid attribute identifier for filter ('.get_class($attribute).')'); | |
} | |
return $this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment