TableQueryExecutor::buildSelectSql()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace Queryr\TermStore;
4
5
use Doctrine\DBAL\Connection;
6
7
/**
8
 * Package private.
9
 *
10
 * @licence GNU GPL v2+
11
 * @author Jeroen De Dauw < [email protected] >
12
 */
13
class TableQueryExecutor {
14
15
	private $connection;
16
	private $tableName;
17
18 16
	public function __construct( Connection $connection, $tableName ) {
19 16
		$this->connection = $connection;
20 16
		$this->tableName = $tableName;
21 16
	}
22
23 15
	public function selectOneField( $fieldName, array $conditions = [] ) {
24 15
		return $this->selectOne( [ $fieldName ], $conditions )[$fieldName];
25
	}
26
27 15
	public function selectOne( array $fieldNames = null, array $conditions = [] ) {
28 15
		$statement = $this->executeSelect( $fieldNames, $conditions, 1 );
29
30 15
		$result = $statement->fetch();
31 15
		return $result === false ? null : $result;
32
	}
33
34 3
	public function select( array $fieldNames = null, array $conditions = [] ) {
35 3
		$statement = $this->executeSelect( $fieldNames, $conditions );
36 3
		return $statement->fetchAll();
37
	}
38
39 3
	public function selectField( $fieldName, array $conditions = [] ) {
40 3
		return array_map(
41 3
			function( array $resultRow ) use ( $fieldName ) {
42 1
				return $resultRow[$fieldName];
43 3
			},
44 3
			$this->select( [ $fieldName ], $conditions )
45
		);
46
	}
47
48 16
	private function executeSelect( array $fieldNames = null, array $conditions = [], $limit = null ) {
49 16
		$sql = $this->buildSelectSql( $fieldNames, $conditions, $limit );
50
51 16
		$statement = $this->connection->prepare( $sql );
52 16
		$statement->execute( array_values( $conditions ) );
53
54 16
		return $statement;
55
	}
56
57 16
	private function buildSelectSql( array $fieldNames = null, array $conditions = [], $limit = null ) {
58 16
		$fieldSql = $this->getFieldSql( $fieldNames );
59 16
		$conditionSql = $this->getConditionSql( $conditions );
60
61 16
		$sql = 'SELECT ' . $fieldSql . ' FROM ' . $this->tableName . ' WHERE ' . $conditionSql;
62
63 16
		if ( $limit !== null ) {
64 15
			$sql .= ' LIMIT ' . (int)$limit;
65
		}
66
67 16
		return $sql;
68
	}
69
70 16
	private function getFieldSql( array $fields = null ) {
71 16
		return $fields === null || $fields === [] ? '*' : implode( ', ', (array)$fields );
72
	}
73
74 16
	private function getConditionSql( array $conditions ) {
75 16
		$wherePredicates = [];
76
77 16
		foreach ( $conditions as $columnName => $columnValue ) {
78 16
			$wherePredicates[] = $columnName . ' = ?';
79
		}
80
81 16
		return implode( ' AND ', $wherePredicates );
82
	}
83
84
}
85