1
|
|
|
<?php |
2
|
|
|
namespace Kir\MySQL\Builder\Traits; |
3
|
|
|
|
4
|
|
|
trait OrderByBuilder { |
5
|
|
|
use AbstractDB; |
6
|
|
|
|
7
|
|
|
/** @var array */ |
8
|
|
|
private $orderBy = array(); |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @param string $expression |
12
|
|
|
* @param string $direction |
13
|
|
|
* @return $this |
14
|
|
|
*/ |
15
|
|
|
public function orderBy($expression, $direction = 'asc') { |
16
|
|
|
if(strtolower($direction) != 'desc') { |
17
|
|
|
$direction = 'ASC'; |
18
|
|
|
} |
19
|
|
|
if(is_array($expression)) { |
20
|
|
|
if(!count($expression)) { |
21
|
|
|
return $this; |
22
|
|
|
} |
23
|
|
|
$arguments = array( |
24
|
|
|
$expression[0], |
25
|
|
|
array_slice($expression, 1) |
26
|
|
|
); |
27
|
|
|
$expression = call_user_func_array(array($this->db(), 'quoteExpression'), $arguments); |
28
|
|
|
} |
29
|
|
|
$this->orderBy[] = array($expression, $direction); |
30
|
|
|
return $this; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
*/ |
35
|
|
|
public function orderByValues($fieldName, array $values) { |
36
|
|
|
$expr = []; |
37
|
|
|
foreach(array_values($values) as $idx => $value) { |
38
|
|
|
$expr[] = $this->db()->quoteExpression("WHEN ? THEN ?", array($value, $idx)); |
39
|
|
|
} |
40
|
|
|
$this->orderBy[] = array(sprintf("CASE %s\n\t\t%s\n\tEND", $this->db()->quoteField($fieldName), join("\n\t\t", $expr)), 'ASC'); |
41
|
|
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $query |
46
|
|
|
* @return string |
47
|
|
|
*/ |
48
|
|
|
protected function buildOrder($query) { |
49
|
|
|
if(!count($this->orderBy)) { |
50
|
|
|
return $query; |
51
|
|
|
} |
52
|
|
|
$query .= "ORDER BY\n"; |
53
|
|
|
$arr = array(); |
54
|
|
|
foreach($this->orderBy as $order) { |
55
|
|
|
list($expression, $direction) = $order; |
56
|
|
|
$arr[] = sprintf("\t%s %s", $expression, strtoupper($direction)); |
57
|
|
|
} |
58
|
|
|
return $query.join(",\n", $arr)."\n"; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|