Skip to content

Instantly share code, notes, and snippets.

@tom--
Last active December 30, 2015 20:19
Show Gist options
  • Select an option

  • Save tom--/7880120 to your computer and use it in GitHub Desktop.

Select an option

Save tom--/7880120 to your computer and use it in GitHub Desktop.
MyDbCriteria adds prefix match searching to Yii’s CDbCriteria
<?php
class MyDbCriteria extends CDbCriteria
{
/**
* Adds a prefix match comparison to the {@link CDbCriteria::condition} property.
* The search condition is of the form
* - "column LIKE 'value%'", or
* - "column NOT LIKE 'value%'"
* depending onthe $like parameter.
* The $value parameter is escaped as in {@link CDbCriteria::addSearchCondition}.
*
* @param string $column the name of the column to be searched.
* @param string $value the prefix value to be compared with.
* @param string $operator the operator used to concatenate the new condition with the existing one.
* Defaults to 'AND'.
* @param string $like the LIKE operator. Defaults to 'LIKE'. You may also set this to be 'NOT LIKE'.
*
* @return CDbCriteria
*/
public function addPrefixCondition($column, $value, $operator = 'AND', $like = 'LIKE')
{
$value = strtr($value, array('%' => '\%', '_' => '\_', '\\' => '\\\\')) . '%';
return $this->addSearchCondition($column, $value, false, $operator, $like);
}
/**
* Appends a comparison expression to the {@link condition}.
* This method is the same as {@link CDbCriteria::compare} except that it adds prefix match
* comparison and operators. To add a prefix match use the <code>^</code> operator or to
* negate the search use <code>!^</code>. Thus if $value is:
* - <code>^keyword</code> the condition will match rows in which the column starts with "keyword"
* - <code>!^keyword</code> the condition matches rows in which the column does not start with "keyword"
*
* For all other details see: {@link CDbCriteria::compare}.
*
* @param string $column
* @param mixed $value
* @param bool $partialMatch
* @param string $operator
* @param bool $escape
*
* @return CDbCriteria
*/
public function compare($column, $value, $partialMatch = false, $operator = 'AND', $escape = true)
{
if ($partialMatch && $escape && is_scalar($value) && preg_match('/^(!)?\^(.*)$/', $value, $matches)) {
$like = $matches[1] === '!' ? 'NOT LIKE' : 'LIKE';
return $this->addPrefixCondition($column, $matches[2], $operator, $like);
}
return parent::compare($column, $value, $partialMatch, $operator, $escape);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment