OrderBy   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 16
dl 0
loc 61
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getOrderBySyntax() 0 6 2
A orderByDesc() 0 9 2
A orderByExpression() 0 5 1
A orderBy() 0 9 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * Author: Adrian Dumitru
5
 * Date: 4/30/2017 8:26 PM
6
 */
7
8
namespace Qpdb\QueryBuilder\Traits;
9
10
11
use Qpdb\QueryBuilder\Dependencies\QueryException;
12
use Qpdb\QueryBuilder\Dependencies\QueryHelper;
13
use Qpdb\QueryBuilder\Dependencies\QueryStructure;
14
15
/**
16
 * Trait OrderBy
17
 * @package Qpdb\QueryBuilder\Traits
18
 * @property QueryStructure $queryStructure
19
 */
20
trait OrderBy
21
{
22
23
	/**
24
	 * @param $column
25
	 * @param array $allowedColumns
26
	 * @return $this
27
	 * @throws QueryException
28
	 */
29
	public function orderBy( $column, array $allowedColumns = [] )
30
	{
31
		if ( !$this->validateColumn( $column, $allowedColumns ) )
0 ignored issues
show
Bug introduced by
It seems like validateColumn() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

31
		if ( !$this->/** @scrutinizer ignore-call */ validateColumn( $column, $allowedColumns ) )
Loading history...
32
			throw new QueryException( 'Invalid column name in ORDER BY clause', QueryException::QUERY_ERROR_INVALID_COLUMN_NAME );
33
34
		$column = $this->queryStructure->prepare($column);
35
		$this->queryStructure->setElement( QueryStructure::ORDER_BY, $column );
36
37
		return $this;
38
	}
39
40
41
	/**
42
	 * @param $column
43
	 * @param array $allowedColumns
44
	 * @return $this
45
	 * @throws QueryException
46
	 */
47
	public function orderByDesc( $column, array $allowedColumns = [] )
48
	{
49
		if ( !$this->validateColumn( $column, $allowedColumns ) )
50
			throw new QueryException( 'Invalid column name in ORDER BY clause', QueryException::QUERY_ERROR_INVALID_COLUMN_NAME );
51
52
		$column = $this->queryStructure->prepare($column);
53
		$this->queryStructure->setElement( QueryStructure::ORDER_BY, $column . ' DESC' );
54
55
		return $this;
56
	}
57
58
59
	/**
60
	 * @param $expression
61
	 * @return $this
62
	 * @throws QueryException
63
	 */
64
	public function orderByExpression( $expression )
65
	{
66
		$this->queryStructure->setElement( QueryStructure::ORDER_BY, $expression );
67
68
		return $this;
69
	}
70
71
72
	/**
73
	 * @return string
74
	 */
75
	private function getOrderBySyntax()
76
	{
77
		if ( count( $this->queryStructure->getElement( QueryStructure::ORDER_BY ) ) )
78
			return 'ORDER BY ' . QueryHelper::implode( $this->queryStructure->getElement( QueryStructure::ORDER_BY ), ', ' );
79
80
		return '';
81
	}
82
83
}