yii\db\QueryBuilder::buildLikeCondition PHP Method

buildLikeCondition() public method

Creates an SQL expressions with the LIKE operator.
public buildLikeCondition ( string $operator, array $operands, array &$params ) : string
$operator string the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
$operands array an array of two or three operands - The first operand is the column name. - The second operand is a single value or an array of values that column value should be compared with. If it is an empty array the generated expression will be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator is `NOT LIKE` or `OR NOT LIKE`. - An optional third operand can also be provided to specify how to escape special characters in the value(s). The operand should be an array of mappings from the special characters to their escaped counterparts. If this operand is not provided, a default escape mapping will be used. You may use `false` or an empty array to indicate the values are already escaped and no escape should be applied. Note that when using an escape mapping (or the third operand is not provided), the values will be automatically enclosed within a pair of percentage characters.
$params array the binding parameters to be populated
return string the generated SQL expression
    public function buildLikeCondition($operator, $operands, &$params)
    {
        if (!isset($operands[0], $operands[1])) {
            throw new InvalidParamException("Operator '{$operator}' requires two operands.");
        }
        $escape = isset($operands[2]) ? $operands[2] : ['%' => '\\%', '_' => '\\_', '\\' => '\\\\'];
        unset($operands[2]);
        if (!preg_match('/^(AND |OR |)(((NOT |))I?LIKE)/', $operator, $matches)) {
            throw new InvalidParamException("Invalid operator '{$operator}'.");
        }
        $andor = ' ' . (!empty($matches[1]) ? $matches[1] : 'AND ');
        $not = !empty($matches[3]);
        $operator = $matches[2];
        list($column, $values) = $operands;
        if (!is_array($values)) {
            $values = [$values];
        }
        if (empty($values)) {
            return $not ? '' : '0=1';
        }
        if (strpos($column, '(') === false) {
            $column = $this->db->quoteColumnName($column);
        }
        $parts = [];
        foreach ($values as $value) {
            if ($value instanceof Expression) {
                foreach ($value->params as $n => $v) {
                    $params[$n] = $v;
                }
                $phName = $value->expression;
            } else {
                $phName = self::PARAM_PREFIX . count($params);
                $params[$phName] = empty($escape) ? $value : '%' . strtr($value, $escape) . '%';
            }
            $parts[] = "{$column} {$operator} {$phName}";
        }
        return implode($andor, $parts);
    }