Completed
Push — master ( 8e51f6...557b77 )
by Yannick
12:09 queued 04:29
created

Connection   C

Complexity

Total Complexity 68

Size/Duplication

Total Lines 292
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 292
rs 5.6756
c 0
b 0
f 0
wmc 68
lcom 1
cbo 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
D __construct() 0 27 9
A db() 0 11 3
B tableExists() 0 20 5
C connectionExists() 0 24 9
A indexExists() 0 19 4
A getColumnName() 0 16 3
F createDBConnection() 0 77 25
B checkColumnName() 0 33 4
A check_schema_version() 0 19 4
A latest() 0 4 2

How to fix   Complexity   

Complex Class

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.

1
<?php
2
require_once(dirname(__FILE__).'/settings.php');
3
4
class Connection{
5
	public $db = null;
6
	public $dbs = array();
7
	public $latest_schema = 26;
8
	
9
	public function __construct($dbc = null,$dbname = null,$user = null,$pass = null) {
10
	    global $globalDBdriver;
11
	    if ($dbc === null) {
12
		if ($this->db === null && $dbname === null) {
13
		    if ($user === null && $pass === null) {
14
			$this->createDBConnection();
15
		    } else {
16
			$this->createDBConnection(null,$user,$pass);
17
		    }
18
		} else {
19
		    $this->createDBConnection($dbname);
20
		}
21
	    } elseif ($dbname === null || $dbname === 'default') {
22
		$this->db = $dbc;
23
		if ($this->connectionExists() === false) {
24
			/*
25
			echo 'Restart Connection !!!'."\n";
26
			$e = new \Exception;
27
			var_dump($e->getTraceAsString());
28
			*/
29
			$this->createDBConnection();
30
		}
31
	    } else {
32
		//$this->connectionExists();
33
		$this->dbs[$dbname] = $dbc;
34
	    }
35
	}
36
37
	public function db() {
38
		if ($this->db === null) {
39
			$this->__construct();
40
		}
41
		if ($this->db === null) {
42
			echo 'Can\'t connect to database. Check configuration and database status.';
43
			die;
44
		} else {
45
			return $this->db;
46
		}
47
	}
48
49
	/**
50
	* Creates the database connection
51
	*
52
	* @return Boolean of the database connection
53
	*
54
	*/
55
56
	public function createDBConnection($DBname = null, $user = null, $pass = null)
57
	{
58
		global $globalDBdriver, $globalDBhost, $globalDBuser, $globalDBpass, $globalDBname, $globalDebug, $globalDB, $globalDBport, $globalDBTimeOut, $globalDBretry, $globalDBPersistent;
59
		if ($DBname === null) {
60
			if ($user === null && $pass === null) {
61
				$DBname = 'default';
62
				$globalDBSdriver = $globalDBdriver;
63
				$globalDBShost = $globalDBhost;
64
				$globalDBSname = $globalDBname;
65
				$globalDBSuser = $globalDBuser;
66
				$globalDBSpass = $globalDBpass;
67
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
68
				else $globalDBSport = $globalDBport;
69
			} else {
70
				$DBname = 'default';
71
				$globalDBSdriver = $globalDBdriver;
72
				$globalDBShost = $globalDBhost;
73
				$globalDBSname = $globalDBname;
74
				$globalDBSuser = $user;
75
				$globalDBSpass = $pass;
76
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
77
				else $globalDBSport = $globalDBport;
78
			}
79
		} else {
80
			$globalDBSdriver = $globalDB[$DBname]['driver'];
81
			$globalDBShost = $globalDB[$DBname]['host'];
82
			$globalDBSname = $globalDB[$DBname]['name'];
83
			$globalDBSuser = $globalDB[$DBname]['user'];
84
			$globalDBSpass = $globalDB[$DBname]['pass'];
85
			if (isset($globalDB[$DBname]['port'])) $globalDBSport = $globalDB[$DBname]['port'];
86
			else $globalDBSport = 3306;
87
		}
88
		// Set number of try to connect to DB
89
		if (!isset($globalDBretry) || $globalDBretry == '' || $globalDBretry === NULL) $globalDBretry = 5;
90
		$i = 0;
91
		while (true) {
92
			try {
93
				if ($globalDBSdriver == 'mysql') {
94
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;charset=utf8", $globalDBSuser,  $globalDBSpass);
95
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
96
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
97
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
98
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,500);
99
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
100
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
101
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
102
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
103
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
104
					// Workaround against "ONLY_FULL_GROUP_BY" mode
105
					// to enable it : $this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY"');
106
					$this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"');
107
					// Force usage of UTC
108
					$this->dbs[$DBname]->exec('SET SESSION time_zone = "+00:00"');
109
					//$this->dbs[$DBname]->exec('SET @@session.time_zone = "+00:00"');
110
				} else {
111
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;options='--client_encoding=utf8'", $globalDBSuser,  $globalDBSpass);
112
					//$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
113
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
115
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,200);
116
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
117
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
118
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
119
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
120
				}
121
				break;
122
			} catch(PDOException $e) {
123
				$i++;
124
				if (isset($globalDebug) && $globalDebug) echo $e->getMessage()."\n";
125
				//exit;
126
				if ($i > $globalDBretry) return false;
127
				//return false;
128
			}
129
		}
130
		if ($DBname === 'default') $this->db = $this->dbs['default'];
131
		return true;
132
	}
133
134
	public function tableExists($table)
135
	{
136
		global $globalDBdriver, $globalDBname;
137
		if ($globalDBdriver == 'mysql') {
138
			$query = "SHOW TABLES LIKE '".$table."'";
139
		} else {
140
			$query = "SELECT * FROM pg_catalog.pg_tables WHERE tablename = '".$table."'";
141
		}
142
		if ($this->db == NULL) return false;
143
		try {
144
			//$Connection = new Connection();
145
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
146
		} catch(PDOException $e) {
147
			return false;
148
		}
149
		if($results->rowCount()>0) {
150
		    return true; 
151
		}
152
		else return false;
153
	}
154
155
	public function connectionExists()
156
	{
157
		global $globalDBdriver, $globalDBCheckConnection;
158
		if (isset($globalDBCheckConnection) && $globalDBCheckConnection === FALSE) return true;
159
		$query = "SELECT 1 + 1";
160
		if ($this->db === null) return false;
161
		try {
162
			$sum = @$this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
163
			if ($sum instanceof \PDOStatement) {
164
				$sum = $sum->fetchColumn(0);
165
			} else $sum = 0;
166
			if (intval($sum) !== 2) {
167
			     return false;
168
			}
169
			
170
		} catch(PDOException $e) {
171
			if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
172
            			throw $e;
173
	                }
174
	                //echo 'error ! '.$e->getMessage();
175
			return false;
176
		}
177
		return true; 
178
	}
179
180
	/*
181
	* Check if index exist
182
	*/
183
	public function indexExists($table,$index)
184
	{
185
		global $globalDBdriver, $globalDBname;
186
		if ($globalDBdriver == 'mysql') {
187
			$query = "SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='".$table."' AND index_name='".$index."'";
188
		} else {
189
			$query = "SELECT 1 FROM   pg_class c JOIN   pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '".$index."' AND n.nspname = '".$table."'";
190
		}
191
		try {
192
			//$Connection = new Connection();
193
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
194
		} catch(PDOException $e) {
195
			return false;
196
		}
197
		if($results->rowCount()>0) {
198
		    return true; 
199
		}
200
		else return false;
201
	}
202
203
	/*
204
	* Get columns name of a table
205
	* @return Array all column name in table
206
	*/
207
	public function getColumnName($table)
208
	{
209
		$query = "SELECT * FROM ".$table." LIMIT 0";
210
		try {
211
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
212
		} catch(PDOException $e) {
213
			return "error : ".$e->getMessage()."\n";
214
		}
215
		$columns = array();
216
		$colcnt = $results->columnCount();
217
		for ($i = 0; $i < $colcnt; $i++) {
218
			$col = $results->getColumnMeta($i);
219
			$columns[] = $col['name'];
220
		}
221
		return $columns;
222
	}
223
224
	/*
225
	* Check if a column name exist in a table
226
	* @return Boolean column exist or not
227
	*/
228
	public function checkColumnName($table,$name)
229
	{
230
		global $globalDBdriver, $globalDBname;
231
		if ($globalDBdriver == 'mysql') {
232
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name";
233
		} else {
234
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name";
235
		}
236
			try {
237
				$sth = $this->db()->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare cannot be called on $this->db() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
238
				$sth->execute(array(':database' => $globalDBname,':table' => $table,':name' => $name));
239
			} catch(PDOException $e) {
240
				echo "error : ".$e->getMessage()."\n";
241
			}
242
			$result = $sth->fetch(PDO::FETCH_ASSOC);
243
			if ($result['nb'] > 0) return true;
244
			else return false;
245
/*		} else {
246
			$query = "SELECT * FROM ".$table." LIMIT 0";
247
			try {
248
				$results = $this->db->query($query);
249
			} catch(PDOException $e) {
250
				return "error : ".$e->getMessage()."\n";
251
			}
252
			$colcnt = $results->columnCount();
253
			for ($i = 0; $i < $colcnt; $i++) {
254
				$col = $results->getColumnMeta($i);
255
				if ($name == $col['name']) return true;
256
			}
257
			return false;
258
		}
259
*/
260
	}
261
262
	/*
263
	* Get schema version
264
	* @return integer schema version
265
	*/
266
	public function check_schema_version() {
267
		$version = 0;
268
		if ($this->tableExists('aircraft')) {
269
			if (!$this->tableExists('config')) {
270
	    			$version = '1';
271
	    			return $version;
272
			} else {
273
				$query = "SELECT value FROM config WHERE name = 'schema_version' LIMIT 1";
274
				try {
275
					$sth = $this->db->prepare($query);
276
					$sth->execute();
277
				} catch(PDOException $e) {
278
					return "error : ".$e->getMessage()."\n";
279
				}
280
				$result = $sth->fetch(PDO::FETCH_ASSOC);
281
				return $result['value'];
282
			}
283
		} else return $version;
284
	}
285
	
286
	/*
287
	* Check if schema version is latest_schema
288
	* @return Boolean if latest version or not
289
	*/
290
	public function latest() {
291
	    if ($this->check_schema_version() == $this->latest_schema) return true;
292
	    else return false;
293
	}
294
295
}
296
?>
297