Completed
Push — master ( 27ae86...5d0263 )
by Jean-Christophe
02:00
created

Database::__construct()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 22
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 18
nc 8
nop 8

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
8
/**
9
 * PDO Database class
10
 *
11
 * @author jc
12
 * @version 1.0.0.3
13
 * @package db
14
 *
15
 */
16
class Database {
17
	private $dbType;
18
	private $serverName;
19
	private $port;
20
	private $dbName;
21
	private $user;
22
	private $password;
23
	private $pdoObject;
24
	private $statements = [ ];
25
	private $cache;
26
	private $options;
27
28
	/**
29
	 * Constructor
30
	 *
31
	 * @param string $dbName
32
	 * @param string $serverName
33
	 * @param string $port
34
	 * @param string $user
35
	 * @param string $password
36
	 * @param array $options
37
	 * @param boolean|string $cache
38
	 */
39
	public function __construct($dbType, $dbName, $serverName = "localhost", $port = "3306", $user = "root", $password = "", $options = [], $cache = false) {
40
		$this->dbType = $dbType;
41
		$this->dbName = $dbName;
42
		$this->serverName = $serverName;
43
		$this->port = $port;
44
		$this->user = $user;
45
		$this->password = $password;
46
		if (isset ( $options ["quote"] ))
47
			SqlUtils::$quote = $options ["quote"];
48
		$this->options = $options;
49
		if ($cache !== false) {
50
			if (\is_callable ( $cache )) {
51
				$this->cache = $cache ();
52
			} else {
53
				if (\class_exists ( $cache )) {
54
					$this->cache = new $cache ();
55
				} else {
56
					throw new CacheException ( $cache . " is not a valid value for database cache" );
57
				}
58
			}
59
		}
60
	}
61
62
	/**
63
	 * Creates the PDO instance and realize a safe connection
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
			return false;
72
		}
73
	}
74
	
75
	public function _connect(){
76
		$this->options[\PDO::ATTR_ERRMODE]=\PDO::ERRMODE_EXCEPTION;
77
		$this->pdoObject = new \PDO ( $this->getDSN(), $this->user, $this->password, $this->options );
78
	}
79
	
80
	public function getDSN(){
81
		return $this->dbType . ':dbname=' . $this->dbName . ';host=' . $this->serverName . ';charset=UTF8;port=' . $this->port;
82
	}
83
84
	/**
85
	 * Executes an SQL statement, returning a result set as a PDOStatement object
86
	 *
87
	 * @param string $sql
88
	 * @return \PDOStatement
89
	 */
90
	public function query($sql) {
91
		return $this->pdoObject->query ( $sql );
92
	}
93
94
	/**
95
	 *
96
	 * @param string $tableName
97
	 * @param string $condition
98
	 * @param array|string $fields
99
	 * @param boolean|null $useCache
100
	 * @return array
101
	 */
102
	public function prepareAndExecute($tableName, $condition, $fields, $useCache = NULL) {
103
		$cache = (DbCache::$active && $useCache !== false) || (! DbCache::$active && $useCache === true);
104
		$result = false;
105
		if ($cache) {
106
			$result = $this->cache->fetch ( $tableName, $condition );
107
		}
108
		if ($result === false) {
109
			$fields = SqlUtils::getFieldList ( $fields, $tableName );
0 ignored issues
show
Documentation introduced by
$tableName is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
110
			$statement = $this->getStatement ( "SELECT {$fields} FROM " . $tableName . $condition );
111
			$statement->execute ();
112
			$result = $statement->fetchAll ();
113
			$statement->closeCursor ();
114
			if ($cache) {
115
				$this->cache->store ( $tableName, $condition, $result );
116
			}
117
		}
118
		return $result;
119
	}
120
121
	/**
122
	 *
123
	 * @param string $sql
124
	 * @return \PDOStatement
125
	 */
126
	private function getStatement($sql) {
127
		if (! isset ( $this->statements [$sql] )) {
128
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
129
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
130
		}
131
		return $this->statements [$sql];
132
	}
133
134
	/**
135
	 * Execute an SQL statement and return the number of affected rows (INSERT, UPDATE or DELETE)
136
	 *
137
	 * @param string $sql
138
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
139
	 */
140
	public function execute($sql) {
141
		return $this->pdoObject->exec ( $sql );
142
	}
143
144
	public function getServerName() {
145
		return $this->serverName;
146
	}
147
148
	public function setServerName($serverName) {
149
		$this->serverName = $serverName;
150
	}
151
152
	/**
153
	 * Prepares a statement for execution and returns a statement object
154
	 *
155
	 * @param String $sql
156
	 * @return \PDOStatement
157
	 */
158
	public function prepareStatement($sql) {
159
		return $this->pdoObject->prepare ( $sql );
160
	}
161
162
	/**
163
	 * Sets $value to $parameter
164
	 *
165
	 * @param \PDOStatement $statement
166
	 * @param String $parameter
167
	 * @param mixed $value
168
	 * @return boolean
169
	 */
170
	public function bindValueFromStatement(\PDOStatement $statement, $parameter, $value) {
171
		return $statement->bindValue ( ":" . $parameter, $value );
172
	}
173
174
	/**
175
	 * Returns the last insert id
176
	 *
177
	 * @return integer
178
	 */
179
	public function lastInserId() {
180
		return $this->pdoObject->lastInsertId ();
181
	}
182
183
	public function getTablesName() {
184
		$sql = 'SHOW TABLES';
185
		$query = $this->pdoObject->query ( $sql );
186
		return $query->fetchAll ( \PDO::FETCH_COLUMN );
187
	}
188
189
	/**
190
	 * Returns the number of records in $tableName that respects the condition passed as a parameter
191
	 *
192
	 * @param string $tableName
193
	 * @param string $condition
194
	 *        	Partie suivant le WHERE d'une instruction SQL
195
	 */
196
	public function count($tableName, $condition = '') {
197
		if ($condition != '')
198
			$condition = " WHERE " . $condition;
199
		return $this->query ( "SELECT COUNT(*) FROM " . $tableName . $condition )->fetchColumn ();
200
	}
201
	
202
	public function queryColumn($query){
203
		return $this->query ( $query )->fetchColumn ();
204
	}
205
	
206
	public function fetchAll($query){
207
		return $this->query ( $query )->fetchAll ( \PDO::FETCH_COLUMN );
208
	}
209
	
210
	public function isConnected() {
211
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping());
212
	}
213
214
	public function setDbType($dbType) {
215
		$this->dbType = $dbType;
216
		return $this;
217
	}
218
	
219
	public function ping() {
220
		return (1 === intval($this->pdoObject->query('SELECT 1')->fetchColumn(0)));
221
	}
222
223
	public function getPort() {
224
		return $this->port;
225
	}
226
227
	public function getDbName() {
228
		return $this->dbName;
229
	}
230
231
	public function getUser() {
232
		return $this->user;
233
	}
234
235
	public function getPdoObject() {
236
		return $this->pdoObject;
237
	}
238
	
239
	public static function getAvailableDrivers(){
240
		return \PDO::getAvailableDrivers();
241
	}
242
}
243