1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
trait TraitQuery |
4
|
|
|
{ |
5
|
|
|
/** |
6
|
|
|
* Adds conditions, orderBy and Limits to query. |
7
|
|
|
* |
8
|
|
|
* @param string $query |
9
|
|
|
* @param mixed $cond |
10
|
|
|
* @param array $order |
11
|
|
|
* @param mixed $limit -> 5 or [$start, $count] |
12
|
|
|
* @param bool $useHaving Flag - to use HAVING instead of WHERE |
13
|
|
|
* |
14
|
|
|
* @return string |
15
|
|
|
*/ |
16
|
|
|
protected static function query( |
17
|
|
|
$query, |
18
|
|
|
$cond = null, |
19
|
|
|
array $order = [], |
20
|
|
|
$limit = 0, |
21
|
|
|
$useHaving = false |
22
|
|
|
) { |
23
|
|
|
//Condition: '' | ' (HAVING|WHERE|AND) ' . $cond |
24
|
|
|
self::queryConditions($query, $cond, $useHaving); |
25
|
|
|
|
26
|
|
|
//Order: '' | 'ORDER BY ' . array_keys($order)[0] . ' ' . $order[0] |
27
|
|
|
self::queryOrder($query, $order); |
28
|
|
|
|
29
|
|
|
//Limit: '' | ' LIMIT ' . '(20, 40|20)' |
30
|
|
|
self::queryLimit($query, $limit); |
31
|
|
|
|
32
|
|
|
return $query; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
private static function queryConditions(&$query, $cond, $useHaving) |
36
|
|
|
{ |
37
|
|
|
if (!empty($cond)) { |
38
|
|
|
$clause = !$useHaving ? 'WHERE' : 'HAVING'; |
39
|
|
|
$clue = !strpos($query, $clause) ? $clause : 'AND'; |
40
|
|
|
$query .= (' '.$clue.' '.$cond); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private static function queryOrder(&$query, $order) |
45
|
|
|
{ |
46
|
|
|
if (!empty($order)) { |
47
|
|
|
$arr = array_map(function (&$value, $key) { |
48
|
|
|
return $key.' '.strtoupper($value); |
49
|
|
|
}, $order, array_keys($order)); |
50
|
|
|
$query .= (' ORDER BY '.implode(', ', $arr)); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private static function queryLimit(&$query, $limit) |
55
|
|
|
{ |
56
|
|
|
if (!empty($limit)) { |
57
|
|
|
$value = (is_array($limit) ? implode(', ', $limit) : $limit); |
58
|
|
|
$query .= (' LIMIT '.$value); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|