Skip to content

Instantly share code, notes, and snippets.

@fdcore
Last active September 14, 2015 15:20
Show Gist options
  • Save fdcore/cdaf25375ef3328a5e48 to your computer and use it in GitHub Desktop.
Save fdcore/cdaf25375ef3328a5e48 to your computer and use it in GitHub Desktop.
<?php
protected function parseCondition($field, $value = null, $join = '', $escape = true) {
if (is_string($field)) {
$operator = '';
if (strpos($field, ' ') !== false) {
list($field, $operator) = explode(' ', $field);
}
if (!empty($operator)) {
switch ($operator) {
case '%':
$condition = ' LIKE ';
break;
case '!%':
$condition = ' NOT LIKE ';
break;
case '@':
$condition = ' IN ';
break;
case '!@':
$condition = ' NOT IN ';
break;
case '=':
$condition = ' IS ';
break;
case '!=':
$condition = ' IS NOT ';
break;
default:
$condition = $operator;
}
}
else {
if ($value === null) $condition = ' IS '; else $condition = '=';
}
if (empty($join)) {
$join = ($field{0} == '|') ? ' OR' : ' AND';
}
if (is_array($value)) {
if (strpos($operator, '@') === false) $condition = ' IN ';
$value = '('.implode(',', array_map(array($this, 'quote'), $value)).')';
}
else {
$value = ($escape && !is_numeric($value)) ? $this->quote($value) : $value;
}
if ($value === null) $value = 'NULL';
return $join.' '.str_replace('|', '', $field).$condition.$value;
}
else if (is_array($field)) {
$str = '';
foreach ($field as $key => $value) {
$str .= $this->parseCondition($key, $value, $join, $escape);
$join = '';
}
return $str;
}
else {
throw new Exception('Invalid where condition.');
}
}
@fdcore
Copy link
Author

fdcore commented Sep 14, 2015

$db->from('users')->where('email', null)->many(); // IS NULL
$db->from('users')->where('email !=', null)->many(); // IS NOT NULL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment