SelectFields   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
eloc 30
c 2
b 0
f 0
dl 0
loc 62
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A fieldExpression() 0 8 2
A normalizeFields() 0 10 1
A getSelectFieldsSyntax() 0 6 2
A fields() 0 19 4
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Adrian Dumitru
5
 * Date: 8/15/2017
6
 * Time: 12:15 PM
7
 */
8
9
namespace Qpdb\QueryBuilder\Traits;
10
11
12
use Qpdb\Common\Helpers\Arrays;
13
use Qpdb\Common\Helpers\Strings;
14
use Qpdb\QueryBuilder\Dependencies\QueryException;
15
use Qpdb\QueryBuilder\Dependencies\QueryStructure;
16
17
/**
18
 * Trait SelectFields
19
 * @package Qpdb\QueryBuilder\Traits
20
 * @property QueryStructure $queryStructure
21
 */
22
trait SelectFields
23
{
24
25
26
	public function fields( ...$fields ) {
27
		$fields = Arrays::flattenValues( $this->normalizeFields( $fields ), true );
28
		foreach ( $fields as $field ) {
29
			$field = Strings::removeMultipleSpace( $field, true );
30
			if ( '' === $field ) {
31
				continue;
32
			}
33
			if ( str_word_count( $field ) === 1 ) {
34
				$this->queryStructure->setElement( QueryStructure::FIELDS, $this->queryStructure->prepare( $field ) );
35
			} else {
36
				$fieldParts = explode( ' ', $field );
37
				$fieldName = $this->queryStructure->prepare( $fieldParts[ 0 ] );
38
				array_shift( $fieldParts );
39
				$fieldAlias = $this->queryStructure->prepare( implode( ' ', $fieldParts ) );
40
				$this->fieldExpression( $fieldName, $fieldAlias );
41
			}
42
		}
43
44
		return $this;
45
	}
46
47
	/**
48
	 * @param             $field
49
	 * @param null|string $alias
50
	 * @return $this
51
	 * @throws QueryException
52
	 */
53
	public function fieldExpression( $field, $alias = null ) {
54
		$field = trim( $field );
55
		if ( '' !== $alias ) {
56
			$field .= ' ' . $alias;
57
		}
58
		$this->queryStructure->setElement( QueryStructure::FIELDS, $field );
59
60
		return $this;
61
	}
62
63
	private function normalizeFields( $fields ) {
64
		$array = Arrays::flattenValues( $fields );
65
		$array = (array)$array;
66
		$return = array();
67
		array_walk_recursive( $array, function( $a ) use ( &$return ) {
68
			$a = explode( ',', $a );
69
			$return[] = $a;
70
		} );
71
72
		return $return;
73
	}
74
75
	/**
76
	 * @return string
77
	 */
78
	private function getSelectFieldsSyntax() {
79
		if ( empty( $this->queryStructure->getElement( QueryStructure::FIELDS ) ) ) {
80
			return '*';
81
		}
82
83
		return implode( ', ', (array)$this->queryStructure->getElement( QueryStructure::FIELDS ));
84
	}
85
86
}