Skip to content

Instantly share code, notes, and snippets.

@DanielBorgesOliveira
Created May 31, 2020 16:57
Show Gist options
  • Save DanielBorgesOliveira/d44595218c26f5e7c1856f926d8e3120 to your computer and use it in GitHub Desktop.
Save DanielBorgesOliveira/d44595218c26f5e7c1856f926d8e3120 to your computer and use it in GitHub Desktop.
<?php
function valueToSQL($value) {
switch (gettype($value)) {
case 'string':
return "'" . $value . "'";
case 'boolean':
return $value ? '1' : '0';
case 'integer':
if (is_finite($value)) return $value;
case 'double':
if (is_finite($value)) return $value;
}
}
function rulesMap($rule)
{
if(isset($rule['rules'])){
return "(" . basicRulesetToSQL($rule) . ")";
}
$column = "";
$column = $rule['field'];
switch ($rule['operator']){
case "is null":
case "is not null":
$operator = $rule['operator'];
$value = "";
break;
case "in":
case "not in":
$operator = $rule['operator'];
if (is_array($rule['value']) && sizeof($rule['value']))
$value = array_map('valueToSQL', $rule['value']);
$value = array_filter($value);
$value = join(", ", $temp);
$value .= ")";
$value = "(" . $value;
break;
default:
$operator = $rule['operator'];
$value = valueToSQL($rule['value']);
break;
}
if(isset($column) && isset($value) && isset($operator)){
return "(" . trim($column . " " . $operator . " " . $value) . ")";
}
}
function basicRulesetToSQL($ruleset) {
$temp = array_map('rulesMap', $ruleset['rules']);
$temp = array_filter($temp);
$temp = join(" " . $ruleset['condition'] . " ", $temp);
return $temp;
}
$data = json_decode('{
"condition": "and",
"rules": [
{
"condition": "and",
"rules": [
{
"field": "Born in",
"operator": ">",
"value": "1945"
},
{
"field": "Submission to the party",
"operator": "<",
"value": "1984"
}
]
},
{
"field": "nickname",
"operator": "=",
"value": "6079 Smith W"
},
{
"field": "Name",
"operator": "=",
"value": "Winston Smith"
}
]
}', TRUE);
echo basicRulesetToSQL($data);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment