Completed
Push — master ( 681f8a...cbe892 )
by Jean-Christophe
02:08
created

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