Completed
Push — master ( aef970...c04073 )
by Ron
02:26
created

OrderByBuilder::buildOrder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
rs 9.4286
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
namespace Kir\MySQL\Builder\Traits;
3
4
trait OrderByBuilder {
5
	use AbstractDB;
6
7
	/**
8
	 * @var array
9
	 */
10
	private $orderBy = array();
11
12
	/**
13
	 * @param string $expression
14
	 * @param string $direction
15
	 * @return $this
16
	 */
17
	public function orderBy($expression, $direction = 'asc') {
18
		if(strtolower($direction) != 'desc') {
19
			$direction = 'ASC';
20
		}
21
		if(is_array($expression)) {
22
			if(!count($expression)) {
23
				return $this;
24
			}
25
			$arguments = array(
26
				$expression[0],
27
				array_slice($expression, 1)
28
			);
29
			$expression = call_user_func_array(array($this->db(), 'quoteExpression'), $arguments);
30
		}
31
		$this->orderBy[] = array($expression, $direction);
32
		return $this;
33
	}
34
35
	/**
36
	 * @param string $query
37
	 * @return string
38
	 */
39
	protected function buildOrder($query) {
40
		if(!count($this->orderBy)) {
41
			return $query;
42
		}
43
		$query .= "ORDER BY\n";
44
		$arr = array();
45
		foreach($this->orderBy as $order) {
46
			list($expression, $direction) = $order;
47
			$arr[] = sprintf("\t%s %s", $expression, strtoupper($direction));
48
		}
49
		return $query.join(",\n", $arr)."\n";
50
	}
51
}
52