Pheasant\Database\Binder::magicBind PHP Method

magicBind() public method

Like bind(), but adds some magic: - a=? becomes a IS NULL if passed null - a!=? or a<>? becomes a IS NOT NULL if passed null - a=? becomes a IN (1, 2, 3) if passed array(1, 2, 3) - a!=? or a<>? becomes a NOT IN (1, 2, 3) if passed array(1, 2, 3)
public magicBind ( $sql, array $params = [] ) : string
$params array
return string
    public function magicBind($sql, array $params = array())
    {
        return $this->_bindInto('(?:`\\w+`|\\w+)\\s*(?:!=|=|<>)\\s*\\?|\\?', $sql, $params, function ($binder, $param, $token) use($sql) {
            if ($token == '?') {
                return $binder->sqlValue($param);
            } else {
                if (!preg_match("/^(.+?)(\\s*(?:!=|=|<>)\\s*)(.+?)\$/", $token, $m)) {
                    throw new \InvalidArgumentException("Failed to parse magic token {$token}");
                }
                $lhs = $m[1];
                $op = trim($m[2]);
                $rhs = $m[3];
                if (($op == '!=' || $op == '<>') && is_array($param)) {
                    return $lhs . ' NOT IN ' . $binder->reduce($param);
                }
                if ($op == '=' && is_array($param)) {
                    return $lhs . ' IN ' . $binder->reduce($param);
                }
                if (is_null($param)) {
                    return $lhs . ' IS' . ($op == '=' ? '' : ' NOT') . ' NULL';
                }
                return $lhs . $m[2] . $binder->sqlValue($param);
            }
        });
    }

Usage Example

Example #1
0
 public function testBindWithBackquote()
 {
     $binder = new Binder();
     $this->assertEquals($binder->magicBind('`id`=?', array(1)), "`id`='1'");
 }
All Usage Examples Of Pheasant\Database\Binder::magicBind