Passed
Push — master ( 0be816...793982 )
by Jean-Christophe
02:53
created

Database::__construct()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 8
nop 8
dl 0
loc 18
ccs 0
cts 18
cp 0
crap 30
rs 9.3888
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace Ubiquity\db;
4
5
use Ubiquity\cache\database\DbCache;
6
use Ubiquity\exceptions\CacheException;
7
use Ubiquity\log\Logger;
8
9
/**
10
 * PDO database class
11
 *
12
 * @author jcheron <[email protected]>
13
 * @version 1.0.3
14
 */
15
class Database {
16
	private $dbType;
17
	private $serverName;
18
	private $port;
19
	private $dbName;
20
	private $user;
21
	private $password;
22
	private $pdoObject;
23
	private $statements = [ ];
24
	private $cache;
25
	private $options;
26
27
	/**
28
	 * Constructor
29
	 *
30
	 * @param string $dbName
31
	 * @param string $serverName
32
	 * @param string $port
33
	 * @param string $user
34
	 * @param string $password
35
	 * @param array $options
36
	 * @param boolean|string $cache
37
	 */
38
	public function __construct($dbType, $dbName, $serverName = "127.0.0.1", $port = "3306", $user = "root", $password = "", $options = [], $cache = false) {
39
		$this->dbType = $dbType;
40
		$this->dbName = $dbName;
41
		$this->serverName = $serverName;
42
		$this->port = $port;
43
		$this->user = $user;
44
		$this->password = $password;
45
		if (isset ( $options ["quote"] ))
46
			SqlUtils::$quote = $options ["quote"];
47
		$this->options = $options;
48
		if ($cache !== false) {
49
			if (\is_callable ( $cache )) {
50
				$this->cache = $cache ();
51
			} else {
52
				if (\class_exists ( $cache )) {
53
					$this->cache = new $cache ();
54
				} else {
55
					throw new CacheException ( $cache . " is not a valid value for database cache" );
56
				}
57
			}
58
		}
59
	}
60
61
	/**
62
	 * Creates the PDO instance and realize a safe connection
63
	 *
64
	 * @return boolean true if connection is established
65
	 */
66
	public function connect() {
67
		try {
68
			$this->_connect ();
69
			return true;
70
		} catch ( \PDOException $e ) {
71
			echo $e->getMessage ();
72
			return false;
73
		}
74
	}
75
76
	public function _connect() {
77
		$this->options [\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
78
		$this->pdoObject = new \PDO ( $this->getDSN (), $this->user, $this->password, $this->options );
79
	}
80
81
	public function getDSN() {
82
		return $this->dbType . ':dbname=' . $this->dbName . ';host=' . $this->serverName . ';charset=UTF8;port=' . $this->port;
83
	}
84
85
	/**
86
	 * Executes an SQL statement, returning a result set as a PDOStatement object
87
	 *
88
	 * @param string $sql
89
	 * @return \PDOStatement
90
	 */
91
	public function query($sql) {
92
		return $this->pdoObject->query ( $sql );
93
	}
94
95
	/**
96
	 *
97
	 * @param string $tableName
98
	 * @param string $condition
99
	 * @param array|string $fields
100
	 * @param array $parameters
101
	 * @param boolean|null $useCache
102
	 * @return array
103
	 */
104
	public function prepareAndExecute($tableName, $condition, $fields, $parameters = null, $useCache = NULL) {
105
		$cache = ((DbCache::$active && $useCache !== false) || (! DbCache::$active && $useCache === true));
106
		$result = false;
107
		if ($cache) {
108
			$cKey = $condition;
109
			if (is_array ( $parameters )) {
110
				$cKey .= implode ( ",", $parameters );
111
			}
112
			try {
113
				$result = $this->cache->fetch ( $tableName, $cKey );
114
				Logger::info ( "Cache", "fetching cache for table {$tableName} with condition : {$condition}", "Database::prepareAndExecute", $parameters );
115
			} catch ( \Exception $e ) {
116
				throw new CacheException ( "Cache is not created in Database constructor" );
117
			}
118
		}
119
		if ($result === false) {
120
			if ($fields = SqlUtils::getFieldList ( $fields, $tableName )) {
121
				$result = $this->prepareAndFetchAll ( "SELECT {$fields} FROM `" . $tableName . "`" . $condition, $parameters );
122
				if ($cache) {
123
					$this->cache->store ( $tableName, $cKey, $result );
124
				}
125
			}
126
		}
127
		return $result;
128
	}
129
130
	public function prepareAndFetchAll($sql, $parameters = null) {
131
		$result = false;
132
		$statement = $this->getStatement ( $sql );
133
		if ($statement->execute ( $parameters )) {
134
			Logger::info ( "Database", $sql, "prepareAndFetchAll", $parameters );
135
			$result = $statement->fetchAll ();
136
		}
137
		$statement->closeCursor ();
138
		return $result;
139
	}
140
141
	public function prepareAndFetchAllColumn($sql, $parameters = null, $column = null) {
142
		$result = false;
143
		$statement = $this->getStatement ( $sql );
144
		if ($statement->execute ( $parameters )) {
145
			Logger::info ( "Database", $sql, "prepareAndFetchAllColumn", $parameters );
146
			$result = $statement->fetchAll ( \PDO::FETCH_COLUMN, $column );
147
		}
148
		$statement->closeCursor ();
149
		return $result;
150
	}
151
152
	public function prepareAndFetchColumn($sql, $parameters = null, $columnNumber = null) {
153
		$statement = $this->getStatement ( $sql );
154
		if ($statement->execute ( $parameters )) {
155
			Logger::info ( "Database", $sql, "prepareAndFetchColumn", $parameters );
156
			return $statement->fetchColumn ( $columnNumber );
157
		}
158
		return false;
159
	}
160
161
	/**
162
	 *
163
	 * @param string $sql
164
	 * @return \PDOStatement
165
	 */
166
	private function getStatement($sql) {
167
		if (! isset ( $this->statements [$sql] )) {
168
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
169
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
170
		}
171
		return $this->statements [$sql];
172
	}
173
174
	/**
175
	 * Execute an SQL statement and return the number of affected rows (INSERT, UPDATE or DELETE)
176
	 *
177
	 * @param string $sql
178
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
179
	 */
180
	public function execute($sql) {
181
		return $this->pdoObject->exec ( $sql );
182
	}
183
184
	/**
185
	 *
186
	 * @return string
187
	 * @codeCoverageIgnore
188
	 */
189
	public function getServerName() {
190
		return $this->serverName;
191
	}
192
193
	public function setServerName($serverName) {
194
		$this->serverName = $serverName;
195
	}
196
197
	/**
198
	 * Prepares a statement for execution and returns a statement object
199
	 *
200
	 * @param String $sql
201
	 * @return \PDOStatement
202
	 */
203
	public function prepareStatement($sql) {
204
		return $this->pdoObject->prepare ( $sql );
205
	}
206
207
	/**
208
	 * Sets $value to $parameter
209
	 *
210
	 * @param \PDOStatement $statement
211
	 * @param String $parameter
212
	 * @param mixed $value
213
	 * @return boolean
214
	 */
215
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
216
		return $statement->bindValue ( ":" . $parameter, $value );
217
	}
218
219
	/**
220
	 * Returns the last insert id
221
	 *
222
	 * @return integer
223
	 */
224
	public function lastInserId() {
225
		return $this->pdoObject->lastInsertId ();
226
	}
227
228
	public function getTablesName() {
229
		$sql = 'SHOW TABLES';
230
		$query = $this->pdoObject->query ( $sql );
231
		return $query->fetchAll ( \PDO::FETCH_COLUMN );
232
	}
233
234
	/**
235
	 * Returns the number of records in $tableName that respects the condition passed as a parameter
236
	 *
237
	 * @param string $tableName
238
	 * @param string $condition
239
	 *        	Partie suivant le WHERE d'une instruction SQL
240
	 */
241
	public function count($tableName, $condition = '') {
242
		if ($condition != '')
243
			$condition = " WHERE " . $condition;
244
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
245
	}
246
247
	public function queryColumn($query, $columnNumber = null) {
248
		return $this->query ( $query )->fetchColumn ( $columnNumber );
249
	}
250
251
	public function fetchAll($query) {
252
		return $this->query ( $query )->fetchAll ();
253
	}
254
255
	public function isConnected() {
256
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping ());
257
	}
258
259
	public function setDbType($dbType) {
260
		$this->dbType = $dbType;
261
		return $this;
262
	}
263
264
	public function ping() {
265
		return ($this->pdoObject && 1 === intval ( $this->pdoObject->query ( 'SELECT 1' )->fetchColumn ( 0 ) ));
266
	}
267
268
	/**
269
	 *
270
	 * @return string
271
	 * @codeCoverageIgnore
272
	 */
273
	public function getPort() {
274
		return $this->port;
275
	}
276
277
	/**
278
	 *
279
	 * @return string
280
	 * @codeCoverageIgnore
281
	 */
282
	public function getDbName() {
283
		return $this->dbName;
284
	}
285
286
	/**
287
	 *
288
	 * @return string
289
	 * @codeCoverageIgnore
290
	 */
291
	public function getUser() {
292
		return $this->user;
293
	}
294
295
	public function getPdoObject() {
296
		return $this->pdoObject;
297
	}
298
299
	public static function getAvailableDrivers() {
300
		return \PDO::getAvailableDrivers ();
301
	}
302
303
	/**
304
	 *
305
	 * @return mixed
306
	 * @codeCoverageIgnore
307
	 */
308
	public function getDbType() {
309
		return $this->dbType;
310
	}
311
312
	/**
313
	 *
314
	 * @return string
315
	 * @codeCoverageIgnore
316
	 */
317
	public function getPassword() {
318
		return $this->password;
319
	}
320
321
	/**
322
	 *
323
	 * @return array
324
	 * @codeCoverageIgnore
325
	 */
326
	public function getOptions() {
327
		return $this->options;
328
	}
329
330
	/**
331
	 *
332
	 * @param string $port
333
	 */
334
	public function setPort($port) {
335
		$this->port = $port;
336
	}
337
338
	/**
339
	 *
340
	 * @param string $dbName
341
	 */
342
	public function setDbName($dbName) {
343
		$this->dbName = $dbName;
344
	}
345
346
	/**
347
	 *
348
	 * @param string $user
349
	 */
350
	public function setUser($user) {
351
		$this->user = $user;
352
	}
353
354
	/**
355
	 *
356
	 * @param string $password
357
	 */
358
	public function setPassword($password) {
359
		$this->password = $password;
360
	}
361
362
	/**
363
	 *
364
	 * @param array $options
365
	 */
366
	public function setOptions($options) {
367
		$this->options = $options;
368
	}
369
}
370