Completed
Push — master ( 2d1963...3845e2 )
by Jean-Christophe
02:09
created

Database::prepareAndFetchAllColumn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 3
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 jc
13
 * @version 1.0.0.3
14
 * @package db
15
 *
16
 */
17
class Database {
18
	private $dbType;
19
	private $serverName;
20
	private $port;
21
	private $dbName;
22
	private $user;
23
	private $password;
24
	private $pdoObject;
25
	private $statements = [ ];
26
	private $cache;
27
	private $options;
28
29
	/**
30
	 * Constructor
31
	 *
32
	 * @param string $dbName
33
	 * @param string $serverName
34
	 * @param string $port
35
	 * @param string $user
36
	 * @param string $password
37
	 * @param array $options
38
	 * @param boolean|string $cache
39
	 */
40
	public function __construct($dbType, $dbName, $serverName = "localhost", $port = "3306", $user = "root", $password = "", $options = [], $cache = false) {
41
		$this->dbType = $dbType;
42
		$this->dbName = $dbName;
43
		$this->serverName = $serverName;
44
		$this->port = $port;
45
		$this->user = $user;
46
		$this->password = $password;
47
		if (isset ( $options ["quote"] ))
48
			SqlUtils::$quote = $options ["quote"];
49
		$this->options = $options;
50
		if ($cache !== false) {
51
			if (\is_callable ( $cache )) {
52
				$this->cache = $cache ();
53
			} else {
54
				if (\class_exists ( $cache )) {
55
					$this->cache = new $cache ();
56
				} else {
57
					throw new CacheException ( $cache . " is not a valid value for database cache" );
58
				}
59
			}
60
		}
61
	}
62
63
	/**
64
	 * Creates the PDO instance and realize a safe connection
65
	 * @return boolean true if connection is established
66
	 */
67
	public function connect() {
68
		try{
69
			$this->_connect();
70
			return true;
71
		}catch (\PDOException $e){
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
			$result = $this->cache->fetch ( $tableName, $cKey );
113
			Logger::info("Cache", "fetching cache for table {$tableName} with condition : {$condition}","Database::prepareAndExecute",$parameters);
114
		}
115
		if ($result === false) {
116
			$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...
117
			$result=$this->prepareAndFetchAll("SELECT {$fields} FROM " . $tableName . $condition,$parameters);
118
			if ($cache) {
119
				$this->cache->store ( $tableName, $cKey, $result );
120
			}
121
		}
122
		return $result;
123
	}
124
	
125 View Code Duplication
	public function prepareAndFetchAll($sql,$parameters=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
		$result=false;
127
		$statement=$this->getStatement($sql);
128
		if($statement->execute ($parameters)){
129
			Logger::info("Database", $sql,"prepareAndFetchAll",$parameters);
130
			$result = $statement->fetchAll ();
131
		}
132
		$statement->closeCursor ();
133
		return $result;
134
	}
135
	
136 View Code Duplication
	public function prepareAndFetchAllColumn($sql,$parameters=null,$column=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
	private function getStatement($sql) {
162
		if (! isset ( $this->statements [$sql] )) {
163
			$this->statements [$sql] = $this->pdoObject->prepare ( $sql );
164
			$this->statements [$sql]->setFetchMode ( \PDO::FETCH_ASSOC );
165
		}
166
		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
	public function setServerName($serverName) {
184
		$this->serverName = $serverName;
185
	}
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
	public function isConnected() {
246
		return ($this->pdoObject !== null && $this->pdoObject instanceof \PDO && $this->ping());
247
	}
248
249
	public function setDbType($dbType) {
250
		$this->dbType = $dbType;
251
		return $this;
252
	}
253
	
254
	public function ping() {
255
		return (1 === intval($this->pdoObject->query('SELECT 1')->fetchColumn(0)));
256
	}
257
258
	public function getPort() {
259
		return $this->port;
260
	}
261
262
	public function getDbName() {
263
		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