CI_DB_mysqli_driver   F
last analyzed

Complexity

Total Complexity 63

Size/Duplication

Total Lines 471
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 471
rs 3.6585
c 0
b 0
f 0
wmc 63

20 Methods

Rating   Name   Duplication   Size   Complexity  
F db_connect() 0 102 28
A __construct() 0 3 1
A _from_tables() 0 8 3
A _close() 0 3 1
A _execute() 0 3 1
A _trans_rollback() 0 9 2
A error() 0 11 2
A _list_tables() 0 10 3
A _trans_commit() 0 9 2
A _escape_str() 0 3 1
A reconnect() 0 4 3
A version() 0 8 2
A _db_set_charset() 0 3 1
A _prep_query() 0 8 3
A db_select() 0 15 3
B field_data() 0 24 3
A insert_id() 0 3 1
A _trans_begin() 0 4 1
A _list_columns() 0 3 1
A affected_rows() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like CI_DB_mysqli_driver 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.

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 CI_DB_mysqli_driver, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
9
 * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
32
 * @copyright	Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 1.3.0
36
 * @filesource
37
 */
38
namespace Rioxygen\CiCoreDatabase\Mysql;
39
40
use Rioxygen\CiCoreDatabase\CI_DB_driver;
41
use \stdClass;
42
43
/**
44
 * MySQLi Database Adapter Class
45
 *
46
 * Note: _DB is an extender class that the app controller
47
 * creates dynamically based on whether the query builder
48
 * class is being used or not.
49
 *
50
 * @package		CodeIgniter
51
 * @subpackage	Drivers
52
 * @category	Database
53
 * @author		EllisLab Dev Team
54
 * @link		https://codeigniter.com/user_guide/database/
55
 */
56
class CI_DB_mysqli_driver extends CI_DB_driver {
57
    /**
58
     * Database driver
59
     *
60
     * @var string
61
     */
62
    public $dbdriver = 'mysqli';
63
    /**
64
     * Compression flag
65
     *
66
     * @var bool
67
     */
68
    public $compress = FALSE;
69
    /**
70
     * DELETE hack flag
71
     *
72
     * Whether to use the MySQL "delete hack" which allows the number
73
     * of affected rows to be shown. Uses a preg_replace when enabled,
74
     * adding a bit more processing to all queries.
75
     *
76
     * @var bool
77
     */
78
    public $delete_hack = TRUE;
79
    /**
80
     * Strict ON flag
81
     *
82
     * Whether we're running in strict SQL mode.
83
     *
84
     * @var bool
85
     */
86
    public $stricton;
87
    /**
88
     * Identifier escape character
89
     *
90
     * @var string
91
     */
92
    protected $_escape_char = '`';
93
    /**
94
     * MySQLi object
0 ignored issues
show
Bug introduced by
The type Rioxygen\CiCoreDatabase\Mysql\MySQLi was not found. Did you mean MySQLi? If so, make sure to prefix the type with \.
Loading history...
95
     *
96
     * Has to be preserved without being assigned to $conn_id.
97
     *
98
     * @var MySQLi
99
     */
100
    protected $_mysqli;
101
    /**
102
     * 
103
     * @param array $params
104
     */
105
    public function __construct(array $params)
106
    {
107
        parent::__construct($params);
108
    }
109
110
    /**
111
     * Database connection
112
     *
113
     * @param	bool	$persistent
114
     * @return	object
115
     **/
116
    public function db_connect($persistent = FALSE)
117
    {
118
		// Do we have a socket path?
119
		if ($this->hostname[0] === '/')
120
		{
121
			$hostname = NULL;
122
			$port = NULL;
123
			$socket = $this->hostname;
124
		}
125
		else
126
		{
127
			$hostname = ($persistent === TRUE)
128
				? 'p:'.$this->hostname : $this->hostname;
129
			$port = empty($this->port) ? NULL : $this->port;
130
			$socket = NULL;
131
		}
132
133
		$client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
134
		$this->_mysqli = mysqli_init();
0 ignored issues
show
Documentation Bug introduced by
It seems like mysqli_init() of type mysqli is incompatible with the declared type Rioxygen\CiCoreDatabase\Mysql\MySQLi of property $_mysqli.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
135
136
		$this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
137
138
		if (isset($this->stricton))
139
		{
140
			if ($this->stricton)
141
			{
142
				$this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")');
143
			}
144
			else
145
			{
146
				$this->_mysqli->options(MYSQLI_INIT_COMMAND,
147
					'SET SESSION sql_mode =
148
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
149
					@@sql_mode,
150
					"STRICT_ALL_TABLES,", ""),
151
					",STRICT_ALL_TABLES", ""),
152
					"STRICT_ALL_TABLES", ""),
153
					"STRICT_TRANS_TABLES,", ""),
154
					",STRICT_TRANS_TABLES", ""),
155
					"STRICT_TRANS_TABLES", "")'
156
				);
157
			}
158
		}
159
160
		if (is_array($this->encrypt))
161
		{
162
			$ssl = array();
163
			empty($this->encrypt['ssl_key'])    OR $ssl['key']    = $this->encrypt['ssl_key'];
164
			empty($this->encrypt['ssl_cert'])   OR $ssl['cert']   = $this->encrypt['ssl_cert'];
165
			empty($this->encrypt['ssl_ca'])     OR $ssl['ca']     = $this->encrypt['ssl_ca'];
166
			empty($this->encrypt['ssl_capath']) OR $ssl['capath'] = $this->encrypt['ssl_capath'];
167
			empty($this->encrypt['ssl_cipher']) OR $ssl['cipher'] = $this->encrypt['ssl_cipher'];
168
169
			if ( ! empty($ssl))
170
			{
171
				if (isset($this->encrypt['ssl_verify']))
172
				{
173
					if ($this->encrypt['ssl_verify'])
174
					{
175
						defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE);
176
					}
177
					// Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
178
					// to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
179
					// constant ...
180
					//
181
					// https://secure.php.net/ChangeLog-5.php#5.6.16
182
					// https://bugs.php.net/bug.php?id=68344
183
					elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT'))
184
					{
185
						$client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
186
					}
187
				}
188
189
				$client_flags |= MYSQLI_CLIENT_SSL;
190
				$this->_mysqli->ssl_set(
191
					isset($ssl['key'])    ? $ssl['key']    : NULL,
192
					isset($ssl['cert'])   ? $ssl['cert']   : NULL,
193
					isset($ssl['ca'])     ? $ssl['ca']     : NULL,
194
					isset($ssl['capath']) ? $ssl['capath'] : NULL,
195
					isset($ssl['cipher']) ? $ssl['cipher'] : NULL
196
				);
197
			}
198
		}
199
200
		if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags))
201
		{
202
			// Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails
203
			if (
204
				($client_flags & MYSQLI_CLIENT_SSL)
205
				&& version_compare($this->_mysqli->client_info, '5.7.3', '<=')
206
				&& empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
207
			)
208
			{
209
				$this->_mysqli->close();
210
				$message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
211
				return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->db_debug ?...sage, '', TRUE) : FALSE returns the type false|string which is incompatible with the documented return type object.
Loading history...
212
			}
213
214
			return $this->_mysqli;
215
		}
216
217
		return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return FALSE returns the type false which is incompatible with the documented return type object.
Loading history...
218
    }
219
220
	// --------------------------------------------------------------------
221
222
    /**
223
     * Reconnect
224
     * Keep / reestablish the db connection if no queries have been
225
     * sent for a length of time exceeding the server's idle timeout
226
     * @return void
227
     */
228
    public function reconnect()
229
    {
230
        if ($this->conn_id !== FALSE && $this->conn_id->ping() === FALSE) {
231
            $this->conn_id = FALSE;
0 ignored issues
show
Documentation Bug introduced by
It seems like FALSE of type false is incompatible with the declared type object|resource of property $conn_id.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
232
        }
233
    }
234
	/**
235
	 * Select the database
236
	 *
237
	 * @param	string	$database
238
	 * @return	bool
239
	 */
240
	public function db_select($database = '')
241
	{
242
		if ($database === '')
243
		{
244
			$database = $this->database;
245
		}
246
247
		if ($this->conn_id->select_db($database))
248
		{
249
			$this->database = $database;
250
			$this->data_cache = array();
251
			return TRUE;
252
		}
253
254
		return FALSE;
255
	}
256
257
	// --------------------------------------------------------------------
258
259
	/**
260
	 * Set client character set
261
	 *
262
	 * @param	string	$charset
263
	 * @return	bool
264
	 */
265
	protected function _db_set_charset($charset)
266
	{
267
		return $this->conn_id->set_charset($charset);
268
	}
269
270
	// --------------------------------------------------------------------
271
272
	/**
273
	 * Database version number
274
	 *
275
	 * @return	string
276
	 */
277
	public function version()
278
	{
279
		if (isset($this->data_cache['version']))
280
		{
281
			return $this->data_cache['version'];
282
		}
283
284
		return $this->data_cache['version'] = $this->conn_id->server_info;
285
	}
286
287
	// --------------------------------------------------------------------
288
289
	/**
290
	 * Execute the query
291
	 *
292
	 * @param	string	$sql	an SQL query
293
	 * @return	mixed
294
	 */
295
	protected function _execute($sql)
296
	{
297
		return $this->conn_id->query($this->_prep_query($sql));
298
	}
299
300
	// --------------------------------------------------------------------
301
302
    /**
303
     * Prep the query
304
     *
305
     * If needed, each database adapter can prep the query string
306
     *
307
     * @param   string $sql an SQL query
308
     * @return  string
309
     */
310
    protected function _prep_query($sql)
311
    {
312
        // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
313
        // modifies the query so that it a proper number of affected rows is returned.
314
        if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) {
315
                return trim($sql).' WHERE 1=1';
316
        }
317
        return $sql;
318
    }
319
    /**
320
     * Begin Transaction
321
     *
322
     * @return bool
323
     */
324
    protected function _trans_begin()
325
    {
326
        $this->conn_id->autocommit(FALSE);
327
        return  $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
328
    }
329
330
	// --------------------------------------------------------------------
331
332
	/**
333
	 * Commit Transaction
334
	 *
335
	 * @return	bool
336
	 */
337
	protected function _trans_commit()
338
	{
339
		if ($this->conn_id->commit())
340
		{
341
			$this->conn_id->autocommit(TRUE);
342
			return TRUE;
343
		}
344
345
		return FALSE;
346
	}
347
348
	// --------------------------------------------------------------------
349
350
	/**
351
	 * Rollback Transaction
352
	 *
353
	 * @return	bool
354
	 */
355
	protected function _trans_rollback()
356
	{
357
		if ($this->conn_id->rollback())
358
		{
359
			$this->conn_id->autocommit(TRUE);
360
			return TRUE;
361
		}
362
363
		return FALSE;
364
	}
365
366
	// --------------------------------------------------------------------
367
368
	/**
369
	 * Platform-dependent string escape
370
	 *
371
	 * @param	string
372
	 * @return	string
373
	 */
374
	protected function _escape_str($str)
375
	{
376
		return $this->conn_id->real_escape_string($str);
377
	}
378
379
	// --------------------------------------------------------------------
380
381
	/**
382
	 * Affected Rows
383
	 *
384
	 * @return	int
385
	 */
386
	public function affected_rows()
387
	{
388
		return $this->conn_id->affected_rows;
389
	}
390
391
	// --------------------------------------------------------------------
392
393
	/**
394
	 * Insert ID
395
	 *
396
	 * @return	int
397
	 */
398
	public function insert_id()
399
	{
400
		return $this->conn_id->insert_id;
401
	}
402
403
	// --------------------------------------------------------------------
404
405
	/**
406
	 * List table query
407
	 *
408
	 * Generates a platform-specific query string so that the table names can be fetched
409
	 *
410
	 * @param	bool	$prefix_limit
411
	 * @return	string
412
	 */
413
	protected function _list_tables($prefix_limit = FALSE)
414
	{
415
		$sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database);
416
417
		if ($prefix_limit !== FALSE && $this->dbprefix !== '')
418
		{
419
			return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
420
		}
421
422
		return $sql;
423
	}
424
425
	// --------------------------------------------------------------------
426
427
	/**
428
	 * Show column query
429
	 *
430
	 * Generates a platform-specific query string so that the column names can be fetched
431
	 *
432
	 * @param	string	$table
433
	 * @return	string
434
	 */
435
	protected function _list_columns($table = '')
436
	{
437
		return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE);
438
	}
439
440
	// --------------------------------------------------------------------
441
442
	/**
443
	 * Returns an object with field data
444
	 *
445
	 * @param	string	$table
446
	 * @return	array
447
	 */
448
	public function field_data($table)
449
	{
450
		if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE)
451
		{
452
			return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return FALSE returns the type false which is incompatible with the documented return type array.
Loading history...
453
		}
454
		$query = $query->result_object();
455
456
		$retval = array();
457
		for ($i = 0, $c = count($query); $i < $c; $i++)
458
		{
459
			$retval[$i]			= new stdClass();
460
			$retval[$i]->name		= $query[$i]->Field;
461
462
			sscanf($query[$i]->Type, '%[a-z](%d)',
463
				$retval[$i]->type,
464
				$retval[$i]->max_length
465
			);
466
467
			$retval[$i]->default		= $query[$i]->Default;
468
			$retval[$i]->primary_key	= (int) ($query[$i]->Key === 'PRI');
469
		}
470
471
		return $retval;
472
	}
473
474
	// --------------------------------------------------------------------
475
476
	/**
477
	 * Error
478
	 *
479
	 * Returns an array containing code and message of the last
480
	 * database error that has occurred.
481
	 *
482
	 * @return	array
483
	 */
484
	public function error()
485
	{
486
		if ( ! empty($this->_mysqli->connect_errno))
487
		{
488
			return array(
489
				'code'    => $this->_mysqli->connect_errno,
490
				'message' => $this->_mysqli->connect_error
491
			);
492
		}
493
494
		return array('code' => $this->conn_id->errno, 'message' => $this->conn_id->error);
495
	}
496
497
	// --------------------------------------------------------------------
498
499
	/**
500
	 * FROM tables
501
	 *
502
	 * Groups tables in FROM clauses if needed, so there is no confusion
503
	 * about operator precedence.
504
	 *
505
	 * @return	string
506
	 */
507
	protected function _from_tables()
508
	{
509
		if ( ! empty($this->qb_join) && count($this->qb_from) > 1)
0 ignored issues
show
Bug Best Practice introduced by
The property qb_from does not exist on Rioxygen\CiCoreDatabase\Mysql\CI_DB_mysqli_driver. Did you maybe forget to declare it?
Loading history...
510
		{
511
			return '('.implode(', ', $this->qb_from).')';
512
		}
513
514
		return implode(', ', $this->qb_from);
515
	}
516
517
	// --------------------------------------------------------------------
518
519
	/**
520
	 * Close DB Connection
521
	 *
522
	 * @return	void
523
	 */
524
	protected function _close()
525
	{
526
		$this->conn_id->close();
527
	}
528
529
}
530