-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryParser.php
90 lines (76 loc) · 2.17 KB
/
QueryParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* Utility class for converting a stringified JSON object into a where-clause
* fragment.
* by: Solodev - Shawn Moore, Ross Williams, Allen Johnson
* webpage: http://www.ocoa.com
*/
class QueryParser
{
/**
* Primary entry point. Given a JSON formatted string, return a SQL where
* clause fragment.
*
* @param \string $query_str JSON formatted string
* @return \string Returns a where clause fragment
*/d
public static function parse($query_str) {
return QueryParser::toFragment(json_decode($query_str));
}
private static function toFragment($values, $op='and') {
$res = '';
if (is_object($values)) {
$res = QueryParser::objectToFragment($values);
} else if (is_array($values)) {
$res = QueryParser::arrayToFragment($values, $op);
}
return $res;
}
private static function arrayToFragment($array, $op='and') {
$len = count($array);
$res = '';
foreach ($array as $idx => $val) {
$res .= QueryParser::toFragment($val);
if ($idx < $len - 1) {
$res .= ' ' . $op . ' ';
}
}
return $res;
}
private static function objectToFragment($obj, $op='and') {
$arr = (array) $obj;
$len = count($arr);
$res = '';
if ($len > 0) {
$res .= '(';
foreach (array_keys($arr) as $i => $key) {
$val = $arr[$key];
if ('$or' === $key) {
$res .= QueryParser::toFragment($val, 'or');
} else if ('$and' === $key) {
$res .= QueryParser::toFragment($val, 'and');
} else {
if (is_object($val)) {
switch (key($val)) {
case '$elemMatch':
$res .= QueryParser::toFragment($val, 'and');
break;
case '$regex':
$res .= sprintf("%s REGEXP '%s'", $key, $val->{key($val)});
break;
case '$ne':
$res .= sprintf("%s != '%s'", $key, $val->{key($val)});
break;
}
} else {
$GLOBALS[$key] = $val;
$res .= "$key = '$val'";
}
}
if ($i < $len - 1) { $res .= ' and '; }
}
$res .= ')';
}
return $res;
}
}