Passed
Push — master ( 0a8819...fef2b8 )
by Jean-Christophe
11:44
created

DatabaseOperationsTrait::prepareAndExecute()   B

Complexity

Conditions 9
Paths 65

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9.0197

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 22
ccs 15
cts 16
cp 0.9375
rs 8.0555
cc 9
nc 65
nop 5
crap 9.0197
1
<?php
2
3
namespace Ubiquity\db\traits;
4
5
use Ubiquity\log\Logger;
6
use Ubiquity\cache\database\DbCache;
7
use Ubiquity\exceptions\CacheException;
8
9
/**
10
 * Ubiquity\db\traits$DatabaseOperationsTrait
11
 * This class is part of Ubiquity
12
 *
13
 * @author jcheron <[email protected]>
14
 * @version 1.0.2
15
 * @property \PDO $pdoObject
16
 * @property mixed $cache
17
 * @property array $options
18
 */
19
trait DatabaseOperationsTrait {
20
	private $statements = [ ];
21
	private $updateStatements = [ ];
22
23
	abstract public function getDSN();
24
25 2
	public function getPdoObject() {
26 2
		return $this->pdoObject;
27
	}
28
29 84
	public function _connect() {
30 84
		$this->options [\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
31 84
		$this->pdoObject = new \PDO ( $this->getDSN (), $this->user, $this->password, $this->options );
32 84
	}
33
34
	/**
35
	 * Executes an SQL statement, returning a result set as a PDOStatement object
36
	 *
37
	 * @param string $sql
38
	 * @return \PDOStatement|boolean
39
	 */
40 7
	public function query($sql) {
41 7
		return $this->pdoObject->query ( $sql );
42
	}
43
44
	/**
45
	 *
46
	 * @param string $tableName
47
	 * @param string $condition
48
	 * @param array|string $fields
49
	 * @param array $parameters
50
	 * @param boolean|null $useCache
51
	 * @return array
52
	 */
53 60
	public function prepareAndExecute($tableName, $condition, $fields, $parameters = null, $useCache = NULL) {
54 60
		$cache = ((DbCache::$active && $useCache !== false) || (! DbCache::$active && $useCache === true));
55 60
		$result = false;
56 60
		if ($cache) {
57 18
			$cKey = $condition;
58 18
			if (is_array ( $parameters )) {
59 15
				$cKey .= implode ( ",", $parameters );
60
			}
61
			try {
62 18
				$result = $this->cache->fetch ( $tableName, $cKey );
63 17
				Logger::info ( "Cache", "fetching cache for table {$tableName} with condition : {$condition}", "Database::prepareAndExecute", $parameters );
64 1
			} catch ( \Exception $e ) {
65
				throw new CacheException ( "Cache is not created in Database constructor" );
66
			}
67
		}
68 60
		if ($result === false) {
69 58
			$result = $this->prepareAndFetchAll ( "SELECT {$fields} FROM `" . $tableName . "`" . $condition, $parameters );
70 58
			if ($cache) {
71 15
				$this->cache->store ( $tableName, $cKey, $result );
72
			}
73
		}
74 60
		return $result;
75
	}
76
77 59
	public function prepareAndFetchAll($sql, $parameters = null, $mode = null) {
78 59
		$statement = $this->getStatement ( $sql );
79 59
		if ($statement->execute ( $parameters )) {
80 59
			Logger::info ( "Database", $sql, "prepareAndFetchAll", $parameters );
81 59
			return $statement->fetchAll ( $mode );
82
		}
83
		return false;
84
	}
85
86
	public function prepareAndFetchOne($sql, $parameters = null, $mode = null) {
87
		$statement = $this->getStatement ( $sql );
88
		if ($statement->execute ( $parameters )) {
89
			Logger::info ( "Database", $sql, "prepareAndFetchOne", $parameters );
90
			return $statement->fetch ( $mode );
91
		}
92
		return false;
93
	}
94
95 1
	public function prepareAndFetchAllColumn($sql, $parameters = null, $column = null) {
96 1
		$statement = $this->getStatement ( $sql );
97 1
		if ($statement->execute ( $parameters )) {
98 1
			Logger::info ( "Database", $sql, "prepareAndFetchAllColumn", $parameters );
99 1
			return $statement->fetchAll ( \PDO::FETCH_COLUMN, $column );
100
		}
101
		return false;
102
	}
103
104 24
	public function prepareAndFetchColumn($sql, $parameters = null, $columnNumber = null) {
105 24
		$statement = $this->getStatement ( $sql );
106 24
		if ($statement->execute ( $parameters )) {
107 24
			Logger::info ( "Database", $sql, "prepareAndFetchColumn", $parameters );
108 24
			return $statement->fetchColumn ( $columnNumber );
109
		}
110
		return false;
111
	}
112
113
	/**
114
	 *
115
	 * @param string $sql
116
	 * @return \PDOStatement
117
	 */
118 70
	private function getStatement($sql) {
119 70
		if (! isset ( $this->statements [$sql] )) {
120 70
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
121 70
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
122
		}
123 70
		return $this->statements [$sql];
124
	}
125
126
	/**
127
	 *
128
	 * @param string $sql
129
	 * @return \PDOStatement
130
	 */
131
	private function getUpdateStatement($sql) {
132
		if (! isset ( $this->updateStatements [$sql] )) {
133
			$this->updateStatements [$sql] = $this->pdoObject->prepare ( $sql );
134
		}
135
		return $this->updateStatements [$sql];
136
	}
137
138
	/**
139
	 * Prepares a statement and execute a query for update (INSERT, UPDATE, DELETE...)
140
	 *
141
	 * @param string $sql
142
	 * @param array|null $parameters
143
	 * @return boolean
144
	 */
145
	public function prepareAndExecuteUpdate($sql, $parameters = null) {
146
		return $this->getUpdateStatement ( $sql )->execute ( $parameters );
147
	}
148
149
	/**
150
	 * Execute an SQL statement and return the number of affected rows (INSERT, UPDATE or DELETE)
151
	 *
152
	 * @param string $sql
153
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
154
	 */
155 2
	public function execute($sql) {
156 2
		return $this->pdoObject->exec ( $sql );
157
	}
158
159
	/**
160
	 * Prepares a statement for execution and returns a statement object
161
	 *
162
	 * @param String $sql
163
	 * @return \PDOStatement|boolean
164
	 */
165 16
	public function prepareStatement($sql) {
166 16
		return $this->pdoObject->prepare ( $sql );
167
	}
168
169
	/**
170
	 * Sets $value to $parameter
171
	 *
172
	 * @param \PDOStatement $statement
173
	 * @param String $parameter
174
	 * @param mixed $value
175
	 * @return boolean
176
	 */
177 1
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
178 1
		return $statement->bindValue ( ":" . $parameter, $value );
179
	}
180
181
	/**
182
	 * Returns the last insert id
183
	 *
184
	 * @return string
185
	 */
186 12
	public function lastInserId() {
187 12
		return $this->pdoObject->lastInsertId ();
188
	}
189
190 4
	public function getTablesName() {
191 4
		$sql = 'SHOW TABLES';
192 4
		$query = $this->pdoObject->query ( $sql );
193 4
		return $query->fetchAll ( \PDO::FETCH_COLUMN );
194
	}
195
196
	/**
197
	 * Returns the number of records in $tableName that respects the condition passed as a parameter
198
	 *
199
	 * @param string $tableName
200
	 * @param string $condition Part following the WHERE of an SQL statement
201
	 */
202 1
	public function count($tableName, $condition = '') {
203 1
		if ($condition != '')
204 1
			$condition = " WHERE " . $condition;
205 1
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
206
	}
207
208 4
	public function queryColumn($query, $columnNumber = null) {
209 4
		return $this->query ( $query )->fetchColumn ( $columnNumber );
210
	}
211
212 1
	public function fetchAll($query) {
213 1
		return $this->query ( $query )->fetchAll ();
214
	}
215
216 19
	public function isConnected() {
217 19
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping ());
218
	}
219
220 5
	public function ping() {
221 5
		return ($this->pdoObject && 1 === intval ( $this->pdoObject->query ( 'SELECT 1' )->fetchColumn ( 0 ) ));
222
	}
223
}
224
225