Completed
Push — master ( 01769e...5b8011 )
by Ron
03:23
created

OrderByBuilder::fixDirection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
namespace Kir\MySQL\Builder\Traits;
3
4
use Kir\MySQL\Builder\Expr\OrderBySpecification;
5
6
trait OrderByBuilder {
7
	use AbstractDB;
8
9
	/** @var array */
10
	private $orderBy = array();
11
12
	/**
13
	 * @param string|OrderBySpecification $expression
14
	 * @param string $direction
15
	 * @return $this
16
	 */
17
	public function orderBy($expression, $direction = 'asc') {
18
		if($expression instanceof OrderBySpecification) {
19
			foreach($expression->getFields() as $field) {
20
				$this->addOrder($field[0], $field[1]);
21
			}
22
			return $this;
23
		}
24
		$this->addOrder($expression, $direction);
25
		return $this;
26
	}
27
	
28
	/**
29
	 * @param string $fieldName
30
	 * @param array $values
31
	 * @return $this
32
	 */
33
	public function orderByValues($fieldName, array $values) {
34
		$expr = [];
35
		foreach(array_values($values) as $idx => $value) {
36
			$expr[] = $this->db()->quoteExpression("WHEN ? THEN ?", array($value, $idx));
37
		}
38
		$this->orderBy[] = array(sprintf("CASE %s\n\t\t%s\n\tEND", $this->db()->quoteField($fieldName), join("\n\t\t", $expr)), 'ASC');
39
		return $this;
40
	}
41
42
	/**
43
	 * @param string $query
44
	 * @return string
45
	 */
46
	protected function buildOrder($query) {
47
		if(!count($this->orderBy)) {
48
			return $query;
49
		}
50
		$query .= "ORDER BY\n";
51
		$arr = array();
52
		foreach($this->orderBy as $order) {
53
			list($expression, $direction) = $order;
54
			$arr[] = sprintf("\t%s %s", $expression, strtoupper($direction));
55
		}
56
		return $query.join(",\n", $arr)."\n";
57
	}
58
	
59
	/**
60
	 * @param string $expression
61
	 * @param string $direction
62
	 */
63
	private function addOrder($expression, $direction) {
64
		$direction = $this->fixDirection($direction);
65
		if(is_array($expression)) {
66
			if(!count($expression)) {
67
				return;
68
			}
69
			$arguments = array(
70
				$expression[0],
71
				array_slice($expression, 1)
72
			);
73
			$expression = call_user_func_array(array($this->db(), 'quoteExpression'), $arguments);
74
		}
75
		$this->orderBy[] = array($expression, $direction);
76
	}
77
	
78
	/**
79
	 * @param string $direction
80
	 * @return string
81
	 */
82
	private function fixDirection($direction) {
83
		return strtoupper($direction) !== 'ASC' ? 'DESC' : 'ASC';
84
	}
85
}
86