Passed
Push — master ( 855968...4d0f3d )
by Jean-Christophe
02:26
created

Database::__construct()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 8
nop 8
dl 0
loc 18
ccs 16
cts 16
cp 1
crap 5
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 23
	public function __construct($dbType, $dbName, $serverName = "127.0.0.1", $port = "3306", $user = "root", $password = "", $options = [], $cache = false) {
39 23
		$this->dbType = $dbType;
40 23
		$this->dbName = $dbName;
41 23
		$this->serverName = $serverName;
42 23
		$this->port = $port;
43 23
		$this->user = $user;
44 23
		$this->password = $password;
45 23
		if (isset ( $options ["quote"] ))
46 1
			SqlUtils::$quote = $options ["quote"];
47 23
		$this->options = $options;
48 23
		if ($cache !== false) {
49 1
			if (\is_callable ( $cache )) {
50 1
				$this->cache = $cache ();
51
			} else {
52 1
				if (\class_exists ( $cache )) {
53 1
					$this->cache = new $cache ();
54
				} else {
55 1
					throw new CacheException ( $cache . " is not a valid value for database cache" );
56
				}
57
			}
58
		}
59 23
	}
60
61
	/**
62
	 * Creates the PDO instance and realize a safe connection
63
	 *
64
	 * @return boolean true if connection is established
65
	 */
66 18
	public function connect() {
67
		try {
68 18
			$this->_connect ();
69 18
			return true;
70 1
		} catch ( \PDOException $e ) {
71 1
			echo $e->getMessage ();
72 1
			return false;
73
		}
74
	}
75
76 18
	public function _connect() {
77 18
		$this->options [\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
78 18
		$this->pdoObject = new \PDO ( $this->getDSN (), $this->user, $this->password, $this->options );
79 18
	}
80
81 19
	public function getDSN() {
82 19
		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 4
	public function query($sql) {
92 4
		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 1
	public function prepareAndExecute($tableName, $condition, $fields, $parameters = null, $useCache = NULL) {
105 1
		$cache = ((DbCache::$active && $useCache !== false) || (! DbCache::$active && $useCache === true));
106 1
		$result = false;
107 1
		if ($cache) {
108 1
			$cKey = $condition;
109 1
			if (is_array ( $parameters )) {
110
				$cKey .= implode ( ",", $parameters );
111
			}
112
			try {
113 1
				$result = $this->cache->fetch ( $tableName, $cKey );
114
				Logger::info ( "Cache", "fetching cache for table {$tableName} with condition : {$condition}", "Database::prepareAndExecute", $parameters );
115 1
			} catch ( \Exception $e ) {
116
				throw new CacheException ( "Cache is not created in Database constructor" );
117
			}
118
		}
119 1
		if ($result === false) {
120 1
			if ($fields = SqlUtils::getFieldList ( $fields, $tableName )) {
121 1
				$result = $this->prepareAndFetchAll ( "SELECT {$fields} FROM `" . $tableName . "`" . $condition, $parameters );
122 1
				if ($cache) {
123
					$this->cache->store ( $tableName, $cKey, $result );
124
				}
125
			}
126
		}
127 1
		return $result;
128
	}
129
130 2
	public function prepareAndFetchAll($sql, $parameters = null) {
131 2
		$result = false;
132 2
		$statement = $this->getStatement ( $sql );
133 2
		if ($statement->execute ( $parameters )) {
134 2
			Logger::info ( "Database", $sql, "prepareAndFetchAll", $parameters );
135 2
			$result = $statement->fetchAll ();
136
		}
137 2
		$statement->closeCursor ();
138 2
		return $result;
139
	}
140
141 1
	public function prepareAndFetchAllColumn($sql, $parameters = null, $column = null) {
142 1
		$result = false;
143 1
		$statement = $this->getStatement ( $sql );
144 1
		if ($statement->execute ( $parameters )) {
145 1
			Logger::info ( "Database", $sql, "prepareAndFetchAllColumn", $parameters );
146 1
			$result = $statement->fetchAll ( \PDO::FETCH_COLUMN, $column );
147
		}
148 1
		$statement->closeCursor ();
149 1
		return $result;
150
	}
151
152 1
	public function prepareAndFetchColumn($sql, $parameters = null, $columnNumber = null) {
153 1
		$statement = $this->getStatement ( $sql );
154 1
		if ($statement->execute ( $parameters )) {
155 1
			Logger::info ( "Database", $sql, "prepareAndFetchColumn", $parameters );
156 1
			return $statement->fetchColumn ( $columnNumber );
157
		}
158
		return false;
159
	}
160
161
	/**
162
	 *
163
	 * @param string $sql
164
	 * @return \PDOStatement
165
	 */
166 4
	private function getStatement($sql) {
167 4
		if (! isset ( $this->statements [$sql] )) {
168 4
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
169 4
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
170
		}
171 4
		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 2
	public function execute($sql) {
181 2
		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 3
	public function setServerName($serverName) {
194 3
		$this->serverName = $serverName;
195 3
	}
196
197
	/**
198
	 * Prepares a statement for execution and returns a statement object
199
	 *
200
	 * @param String $sql
201
	 * @return \PDOStatement
202
	 */
203 2
	public function prepareStatement($sql) {
204 2
		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 1
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
216 1
		return $statement->bindValue ( ":" . $parameter, $value );
217
	}
218
219
	/**
220
	 * Returns the last insert id
221
	 *
222
	 * @return integer
223
	 */
224 1
	public function lastInserId() {
225 1
		return $this->pdoObject->lastInsertId ();
226
	}
227
228 1
	public function getTablesName() {
229 1
		$sql = 'SHOW TABLES';
230 1
		$query = $this->pdoObject->query ( $sql );
231 1
		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 1
	public function count($tableName, $condition = '') {
242 1
		if ($condition != '')
243 1
			$condition = " WHERE " . $condition;
244 1
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
245
	}
246
247 1
	public function queryColumn($query, $columnNumber = null) {
248 1
		return $this->query ( $query )->fetchColumn ( $columnNumber );
249
	}
250
251 1
	public function fetchAll($query) {
252 1
		return $this->query ( $query )->fetchAll ();
253
	}
254
255 17
	public function isConnected() {
256 17
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping ());
257
	}
258
259 3
	public function setDbType($dbType) {
260 3
		$this->dbType = $dbType;
261 3
		return $this;
262
	}
263
264 3
	public function ping() {
265 3
		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 1
	public function getPdoObject() {
296 1
		return $this->pdoObject;
297
	}
298
299 1
	public static function getAvailableDrivers() {
300 1
		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 2
	public function setPort($port) {
335 2
		$this->port = $port;
336 2
	}
337
338
	/**
339
	 *
340
	 * @param string $dbName
341
	 */
342 1
	public function setDbName($dbName) {
343 1
		$this->dbName = $dbName;
344 1
	}
345
346
	/**
347
	 *
348
	 * @param string $user
349
	 */
350 2
	public function setUser($user) {
351 2
		$this->user = $user;
352 2
	}
353
354
	/**
355
	 *
356
	 * @param string $password
357
	 */
358 1
	public function setPassword($password) {
359 1
		$this->password = $password;
360 1
	}
361
362
	/**
363
	 *
364
	 * @param array $options
365
	 */
366 1
	public function setOptions($options) {
367 1
		$this->options = $options;
368 1
	}
369
}
370