Passed
Push — master ( d1f5f8...1bb3e8 )
by Jean-Christophe
02:28
created

Database::__construct()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.3183

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 8
nop 8
dl 0
loc 18
ccs 10
cts 16
cp 0.625
crap 6.3183
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 6
	public function __construct($dbType, $dbName, $serverName = "127.0.0.1", $port = "3306", $user = "root", $password = "", $options = [], $cache = false) {
39 6
		$this->dbType = $dbType;
40 6
		$this->dbName = $dbName;
41 6
		$this->serverName = $serverName;
42 6
		$this->port = $port;
43 6
		$this->user = $user;
44 6
		$this->password = $password;
45 6
		if (isset ( $options ["quote"] ))
46
			SqlUtils::$quote = $options ["quote"];
47 6
		$this->options = $options;
48 6
		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 6
	}
60
61
	/**
62
	 * Creates the PDO instance and realize a safe connection
63
	 *
64
	 * @return boolean true if connection is established
65
	 */
66 4
	public function connect() {
67
		try {
68 4
			$this->_connect ();
69 4
			return true;
70
		} catch ( \PDOException $e ) {
71
			echo $e->getMessage ();
72
			return false;
73
		}
74
	}
75
76 4
	public function _connect() {
77 4
		$this->options [\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
78 4
		$this->pdoObject = new \PDO ( $this->getDSN (), $this->user, $this->password, $this->options );
79 4
	}
80
81 5
	public function getDSN() {
82 5
		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 1
	public function query($sql) {
92 1
		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
			$cKey = $condition;
109
			if (is_array ( $parameters )) {
110
				$cKey .= implode ( ",", $parameters );
111
			}
112
			$result = $this->cache->fetch ( $tableName, $cKey );
113
			Logger::info ( "Cache", "fetching cache for table {$tableName} with condition : {$condition}", "Database::prepareAndExecute", $parameters );
114
		}
115 1
		if ($result === false) {
116 1
			$fields = SqlUtils::getFieldList ( $fields, $tableName );
117 1
			$result = $this->prepareAndFetchAll ( "SELECT {$fields} FROM `" . $tableName . "`" . $condition, $parameters );
118 1
			if ($cache) {
119
				$this->cache->store ( $tableName, $cKey, $result );
120
			}
121
		}
122 1
		return $result;
123
	}
124
125 2
	public function prepareAndFetchAll($sql, $parameters = null) {
126 2
		$result = false;
127 2
		$statement = $this->getStatement ( $sql );
128 2
		if ($statement->execute ( $parameters )) {
129 2
			Logger::info ( "Database", $sql, "prepareAndFetchAll", $parameters );
130 2
			$result = $statement->fetchAll ();
131
		}
132 2
		$statement->closeCursor ();
133 2
		return $result;
134
	}
135
136
	public function prepareAndFetchAllColumn($sql, $parameters = null, $column = null) {
137
		$result = false;
138
		$statement = $this->getStatement ( $sql );
139
		if ($statement->execute ( $parameters )) {
140
			Logger::info ( "Database", $sql, "prepareAndFetchAllColumn", $parameters );
141
			$result = $statement->fetchAll ( \PDO::FETCH_COLUMN, $column );
142
		}
143
		$statement->closeCursor ();
144
		return $result;
145
	}
146
147
	public function prepareAndFetchColumn($sql, $parameters = null, $column = null) {
148
		$statement = $this->getStatement ( $sql );
149
		if ($statement->execute ( $parameters )) {
150
			Logger::info ( "Database", $sql, "prepareAndFetchColumn", $parameters );
151
			return $statement->fetchColumn ( $column );
152
		}
153
		return false;
154
	}
155
156
	/**
157
	 *
158
	 * @param string $sql
159
	 * @return \PDOStatement
160
	 */
161 2
	private function getStatement($sql) {
162 2
		if (! isset ( $this->statements [$sql] )) {
163 2
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
164 2
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
165
		}
166 2
		return $this->statements [$sql];
167
	}
168
169
	/**
170
	 * Execute an SQL statement and return the number of affected rows (INSERT, UPDATE or DELETE)
171
	 *
172
	 * @param string $sql
173
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
174
	 */
175
	public function execute($sql) {
176
		return $this->pdoObject->exec ( $sql );
177
	}
178
179
	public function getServerName() {
180
		return $this->serverName;
181
	}
182
183 1
	public function setServerName($serverName) {
184 1
		$this->serverName = $serverName;
185 1
	}
186
187
	/**
188
	 * Prepares a statement for execution and returns a statement object
189
	 *
190
	 * @param String $sql
191
	 * @return \PDOStatement
192
	 */
193
	public function prepareStatement($sql) {
194
		return $this->pdoObject->prepare ( $sql );
195
	}
196
197
	/**
198
	 * Sets $value to $parameter
199
	 *
200
	 * @param \PDOStatement $statement
201
	 * @param String $parameter
202
	 * @param mixed $value
203
	 * @return boolean
204
	 */
205
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
206
		return $statement->bindValue ( ":" . $parameter, $value );
207
	}
208
209
	/**
210
	 * Returns the last insert id
211
	 *
212
	 * @return integer
213
	 */
214
	public function lastInserId() {
215
		return $this->pdoObject->lastInsertId ();
216
	}
217
218
	public function getTablesName() {
219
		$sql = 'SHOW TABLES';
220
		$query = $this->pdoObject->query ( $sql );
221
		return $query->fetchAll ( \PDO::FETCH_COLUMN );
222
	}
223
224
	/**
225
	 * Returns the number of records in $tableName that respects the condition passed as a parameter
226
	 *
227
	 * @param string $tableName
228
	 * @param string $condition
229
	 *        	Partie suivant le WHERE d'une instruction SQL
230
	 */
231
	public function count($tableName, $condition = '') {
232
		if ($condition != '')
233
			$condition = " WHERE " . $condition;
234
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
235
	}
236
237
	public function queryColumn($query) {
238
		return $this->query ( $query )->fetchColumn ();
239
	}
240
241
	public function fetchAll($query) {
242
		return $this->query ( $query )->fetchAll ( \PDO::FETCH_COLUMN );
243
	}
244
245 3
	public function isConnected() {
246 3
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping ());
247
	}
248
249 1
	public function setDbType($dbType) {
250 1
		$this->dbType = $dbType;
251 1
		return $this;
252
	}
253
254
	public function ping() {
255
		return (1 === intval ( $this->pdoObject->query ( 'SELECT 1' )->fetchColumn ( 0 ) ));
256
	}
257
258 1
	public function getPort() {
259 1
		return $this->port;
260
	}
261
262 1
	public function getDbName() {
263 1
		return $this->dbName;
264
	}
265
266
	public function getUser() {
267
		return $this->user;
268
	}
269
270
	public function getPdoObject() {
271
		return $this->pdoObject;
272
	}
273
274
	public static function getAvailableDrivers() {
275
		return \PDO::getAvailableDrivers ();
276
	}
277
278
	/**
279
	 *
280
	 * @return mixed
281
	 */
282
	public function getDbType() {
283
		return $this->dbType;
284
	}
285
286
	/**
287
	 *
288
	 * @return string
289
	 */
290
	public function getPassword() {
291
		return $this->password;
292
	}
293
294
	/**
295
	 *
296
	 * @return array
297
	 */
298
	public function getOptions() {
299
		return $this->options;
300
	}
301
302
	/**
303
	 *
304
	 * @param string $port
305
	 */
306 1
	public function setPort($port) {
307 1
		$this->port = $port;
308 1
	}
309
310
	/**
311
	 *
312
	 * @param string $dbName
313
	 */
314
	public function setDbName($dbName) {
315
		$this->dbName = $dbName;
316
	}
317
318
	/**
319
	 *
320
	 * @param string $user
321
	 */
322
	public function setUser($user) {
323
		$this->user = $user;
324
	}
325
326
	/**
327
	 *
328
	 * @param string $password
329
	 */
330
	public function setPassword($password) {
331
		$this->password = $password;
332
	}
333
334
	/**
335
	 *
336
	 * @param array $options
337
	 */
338
	public function setOptions($options) {
339
		$this->options = $options;
340
	}
341
}
342