Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like db_mysql 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 db_mysql, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
9 | class db_mysql { |
||
10 | const TRANSACTION_SERIALIZABLE = 'SERIALIZABLE'; |
||
11 | const TRANSACTION_REPEATABLE_READ = 'REPEATABLE READ'; |
||
12 | const TRANSACTION_READ_COMMITTED = 'READ COMMITTED'; |
||
13 | const TRANSACTION_READ_UNCOMMITTED = 'READ UNCOMMITTED'; |
||
14 | |||
15 | /** |
||
16 | * Статус соеднения с MySQL |
||
17 | * |
||
18 | * @var bool |
||
19 | */ |
||
20 | public $connected = false; |
||
21 | /** |
||
22 | * Префикс названий таблиц в БД |
||
23 | * |
||
24 | * @var string |
||
25 | */ |
||
26 | public $db_prefix = ''; |
||
27 | /** |
||
28 | * Список таблиц в БД |
||
29 | * |
||
30 | * @var array |
||
31 | */ |
||
32 | public $table_list = array(); |
||
33 | |||
34 | /** |
||
35 | * Настройки БД |
||
36 | * |
||
37 | * @var array |
||
38 | */ |
||
39 | protected $dbsettings = array(); |
||
40 | /** |
||
41 | * Драйвер для прямого обращения к MySQL |
||
42 | * |
||
43 | * @var db_mysql_v5 $driver |
||
44 | */ |
||
45 | public $driver = null; |
||
46 | |||
47 | /** |
||
48 | * Общее время запросов |
||
49 | * |
||
50 | * @var float $time_mysql_total |
||
51 | */ |
||
52 | public $time_mysql_total = 0.0; |
||
53 | |||
54 | /** |
||
55 | * Amount of queries on this DB |
||
56 | * |
||
57 | * @var int |
||
58 | */ |
||
59 | public $queryCount = 0; |
||
60 | |||
61 | public $isWatching = false; |
||
62 | |||
63 | /** |
||
64 | * @var \DBAL\DbTransaction $transaction |
||
65 | */ |
||
66 | protected $transaction; |
||
67 | |||
68 | /** |
||
69 | * Should query check be skipped? |
||
70 | * |
||
71 | * Used for altering scheme of DB |
||
72 | * |
||
73 | * @var bool $skipQueryCheck |
||
74 | */ |
||
75 | protected $skipQueryCheck = false; |
||
76 | |||
77 | /** |
||
78 | * @var SnCache $snCache |
||
79 | */ |
||
80 | public $snCache; |
||
81 | |||
82 | /** |
||
83 | * @var DbRowDirectOperator $operator |
||
84 | */ |
||
85 | protected $operator; |
||
86 | |||
87 | /** |
||
88 | * db_mysql constructor. |
||
89 | * |
||
90 | * @param \Common\GlobalContainer $gc |
||
91 | */ |
||
92 | public function __construct($gc) { |
||
93 | $this->transaction = new \DBAL\DbTransaction($gc, $this); |
||
94 | $this->snCache = new $gc->snCacheClass($gc, $this); |
||
95 | $this->operator = new DbRowDirectOperator($this); |
||
96 | } |
||
97 | |||
98 | public function load_db_settings($configFile = '') { |
||
99 | $dbsettings = array(); |
||
100 | |||
101 | empty($configFile) ? $configFile = SN_ROOT_PHYSICAL . "config" . DOT_PHP_EX : false; |
||
102 | |||
103 | require $configFile; |
||
104 | |||
105 | $this->dbsettings = $dbsettings; |
||
106 | } |
||
107 | |||
108 | /** |
||
109 | * @param null|array $external_db_settings |
||
110 | * |
||
111 | * @return bool |
||
112 | */ |
||
113 | public function sn_db_connect($external_db_settings = null) { |
||
142 | |||
143 | protected function driver_connect() { |
||
144 | if (!is_object($this->driver)) { |
||
145 | classSupernova::$debug->error_fatal('DB Error - No driver for MySQL found!'); |
||
146 | } |
||
147 | |||
148 | if (!method_exists($this->driver, 'mysql_connect')) { |
||
149 | classSupernova::$debug->error_fatal('DB Error - WRONG MySQL driver!'); |
||
150 | } |
||
151 | |||
152 | return $this->driver->mysql_connect($this->dbsettings); |
||
153 | } |
||
154 | |||
155 | public function db_disconnect() { |
||
156 | if ($this->connected) { |
||
157 | $this->connected = !$this->driver_disconnect(); |
||
158 | $this->connected = false; |
||
159 | } |
||
160 | |||
161 | return !$this->connected; |
||
162 | } |
||
163 | |||
164 | /** |
||
165 | * @param string $query |
||
166 | * |
||
167 | * @return mixed|string |
||
168 | */ |
||
169 | public function replaceTablePlaceholders($query) { |
||
170 | $sql = $query; |
||
171 | if (strpos($sql, '{{') !== false) { |
||
172 | foreach ($this->table_list as $tableName) { |
||
173 | $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql); |
||
174 | } |
||
175 | } |
||
176 | |||
177 | return $sql; |
||
178 | } |
||
179 | |||
180 | /** |
||
181 | * @param $query |
||
182 | */ |
||
183 | protected function logQuery($query) { |
||
184 | if (!classSupernova::$config->debug) { |
||
185 | return; |
||
186 | } |
||
187 | |||
188 | $this->queryCount++; |
||
189 | $arr = debug_backtrace(); |
||
190 | $file = end(explode('/', $arr[0]['file'])); |
||
|
|||
191 | $line = $arr[0]['line']; |
||
192 | classSupernova::$debug->add("<tr><th>Query {$this->queryCount}: </th><th>$query</th><th>{$file} @ {$line}</th><th> </th></tr>"); |
||
193 | } |
||
194 | |||
195 | |||
196 | /** |
||
197 | * @return string |
||
198 | */ |
||
199 | public function traceQuery() { |
||
200 | if (!defined('DEBUG_SQL_COMMENT') || constant('DEBUG_SQL_ERROR') !== true) { |
||
201 | return ''; |
||
202 | } |
||
203 | |||
204 | $backtrace = debug_backtrace(); |
||
205 | $sql_comment = classSupernova::$debug->compact_backtrace($backtrace, defined('DEBUG_SQL_COMMENT_LONG')); |
||
206 | |||
207 | if (defined('DEBUG_SQL_ERROR') && constant('DEBUG_SQL_ERROR') === true) { |
||
208 | classSupernova::$debug->add_to_array($sql_comment); |
||
209 | } |
||
210 | |||
211 | $sql_commented = implode("\r\n", $sql_comment); |
||
212 | if (defined('DEBUG_SQL_ONLINE') && constant('DEBUG_SQL_ONLINE') === true) { |
||
213 | classSupernova::$debug->warning($sql_commented, 'SQL Debug', LOG_DEBUG_SQL); |
||
214 | } |
||
215 | |||
216 | return $sql_commented; |
||
217 | } |
||
218 | |||
219 | /** |
||
220 | * @param string $query |
||
221 | * |
||
222 | * @return array|bool|mysqli_result|null |
||
223 | */ |
||
224 | protected function queryDriver($query) { |
||
225 | if (!$this->connected) { |
||
226 | $this->sn_db_connect(); |
||
227 | } |
||
228 | |||
229 | $stringQuery = $query; |
||
230 | $stringQuery = trim($stringQuery); |
||
231 | // You can't do it - 'cause you can break commented statement with line-end comments |
||
232 | // $stringQuery = preg_replace("/\s+/", ' ', $stringQuery); |
||
233 | |||
234 | $this->security_watch_user_queries($stringQuery); |
||
235 | $this->security_query_check_bad_words($stringQuery); |
||
236 | $this->logQuery($stringQuery); |
||
237 | |||
238 | $stringQuery = $this->replaceTablePlaceholders($stringQuery); |
||
239 | |||
240 | $queryTrace = $this->traceQuery(); |
||
241 | |||
242 | $queryResult = null; |
||
243 | try { |
||
244 | $queryResult = $this->db_sql_query($stringQuery . DbSqlHelper::quoteComment($queryTrace)); |
||
245 | if (!$queryResult) { |
||
246 | throw new Exception(); |
||
247 | } |
||
248 | } catch (Exception $e) { |
||
249 | classSupernova::$debug->error($this->db_error() . "<br />{$query}<br />", 'SQL Error'); |
||
250 | } |
||
251 | |||
252 | return $queryResult; |
||
253 | } |
||
254 | |||
255 | |||
256 | // Just wrappers to distinguish query types |
||
257 | /** |
||
258 | * Executes non-data manipulation statements |
||
259 | * |
||
260 | * Can execute queries with check skip |
||
261 | * Honor current state of query checking |
||
262 | * |
||
263 | * @param string $query |
||
264 | * @param bool $skip_query_check |
||
265 | * |
||
266 | * @return array|bool|mysqli_result|null |
||
267 | */ |
||
268 | public function doSql($query, $skip_query_check = false) { |
||
269 | $prevState = $this->skipQueryCheck; |
||
270 | $this->skipQueryCheck = $skip_query_check; |
||
271 | // TODO - disable watch ?? |
||
272 | $result = $this->queryDriver($query); |
||
273 | $this->skipQueryCheck = $prevState; |
||
274 | |||
275 | return $result; |
||
276 | } |
||
277 | |||
278 | |||
279 | // TODO - should be in DbRowDirectOperator eventually |
||
280 | // SQL operations ==================================================================================================== |
||
281 | // SELECTS ----------------------------------------------------------------------------------------------------------- |
||
282 | public function doSelect($query) { |
||
283 | return $this->doSql($query); |
||
284 | } |
||
285 | |||
286 | /** |
||
287 | * DANGER! Fields and Where can be danger |
||
288 | * |
||
289 | * @param string $table |
||
290 | * @param array $fields |
||
291 | * @param array $where |
||
292 | * @param bool $isOneRecord |
||
293 | * |
||
294 | * @return array|bool|mysqli_result|null |
||
295 | * |
||
296 | * TODO - replace with appropriate DbQuery when it's be ready |
||
297 | */ |
||
298 | public function doSelectDanger($table, $fields, $where = array(), $isOneRecord = DB_RECORDS_ALL, $forUpdate = DB_SELECT_PLAIN) { |
||
299 | // TODO - TEMPORARY UNTIL DbQuery |
||
300 | if (!empty($where)) { |
||
301 | foreach ($where as $key => &$value) { |
||
302 | if (!is_int($key)) { |
||
303 | $value = "`$key` = '" . $this->db_escape($value) . "'"; |
||
304 | } |
||
305 | } |
||
306 | } |
||
307 | |||
308 | $query = |
||
309 | "SELECT " . implode(',', $fields) . |
||
310 | " FROM `{{{$table}}}`" . |
||
311 | (!empty($where) ? ' WHERE ' . implode(' AND ', $where) : '') . |
||
312 | ($isOneRecord == DB_RECORD_ONE ? ' LIMIT 1' : '') . |
||
313 | ($forUpdate == DB_SELECT_FOR_UPDATE ? ' FOR UPDATE' : ''); |
||
314 | |||
315 | return $this->doSql($query); |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * @param string $strSql |
||
320 | * |
||
321 | * @return array|null |
||
322 | * |
||
323 | * @deprecated |
||
324 | * TODO - УДАЛИТЬ |
||
325 | * Метод временно находится здесь - слишком много переписывать, что бы его отсюда вынести |
||
326 | */ |
||
327 | public function doSelectFetchArray($strSql) { |
||
330 | |||
331 | |||
332 | |||
333 | // |
||
334 | // INSERT/REPLACE ---------------------------------------------------------------------------------------------------- |
||
335 | public function doInsertComplex($query) { |
||
336 | return $this->doSql($query); |
||
337 | } |
||
338 | |||
339 | // TODO - batch insert and replace here |
||
340 | // перед тем, как переделывать данные из депрекейтов - убедится, что |
||
341 | // null - это null, а не строка'NULL' |
||
342 | |||
343 | /** |
||
344 | * @param string $table |
||
345 | * @param array|array[] $valuesOptionallyKeyByFields |
||
346 | * @param array $fields |
||
347 | * |
||
348 | * @param int $replace - DB_INSERT_PLAIN || DB_INSERT_IGNORE |
||
349 | * |
||
350 | * @return array|bool|mysqli_result|null TODO - избаватьися от $fields. Это поле нужно только при пакетной вставке - а поля вполне можно брать из общего массива |
||
351 | * TODO - избаватьися от $fields. Это поле нужно только при пакетной вставке - а поля вполне можно брать из общего массива |
||
352 | */ |
||
353 | public function doInsertSet($table, $valuesOptionallyKeyByFields, $fields = array(), $replace = DB_INSERT_PLAIN) { |
||
362 | |||
363 | /**+ |
||
364 | * Values should be passed as array of arrays |
||
365 | * |
||
366 | * @param string $table |
||
367 | * @param array[] $valuesBatch |
||
368 | * @param array $fields |
||
369 | * |
||
370 | * @param int $replace |
||
371 | * |
||
372 | * @return array|bool|mysqli_result|null |
||
373 | */ |
||
374 | public function doInsertBatch($table, &$valuesBatch, $fields, $replace) { |
||
377 | |||
378 | // Just to separate INSERTS from REPLACES |
||
379 | /** |
||
380 | * Replaces record in DB |
||
381 | * |
||
382 | * There are no DANGER replace operations |
||
383 | * |
||
384 | * @param string $table |
||
385 | * @param array $fieldsAndValues |
||
386 | * |
||
387 | * @return array|bool|mysqli_result|null |
||
388 | */ |
||
389 | public function doReplaceSet($table, $fieldsAndValues) { |
||
392 | |||
393 | |||
394 | // |
||
395 | // UPDATERS |
||
396 | // Deprecated |
||
397 | public function doUpdateAdjust($strSql) { |
||
400 | |||
401 | public function doUpdateReallyComplex($query) { |
||
404 | |||
405 | /** |
||
406 | * Executes self-contained SQL UPDATE query |
||
407 | * |
||
408 | * Self-contained - means no params used |
||
409 | * Such queries usually used to make large amount of in-base calculations |
||
410 | * |
||
411 | * @param $query |
||
412 | * |
||
413 | * @return array|bool|mysqli_result|null |
||
414 | */ |
||
415 | public function doUpdateSqlNoParam($query) { |
||
418 | |||
419 | |||
420 | /** |
||
421 | * @param $DbQuery DbQuery |
||
422 | */ |
||
423 | protected function doUpdateDbQuery($DbQuery) { |
||
426 | |||
427 | /** |
||
428 | * @param $DbQuery DbQuery |
||
429 | */ |
||
430 | public function doUpdateDbQueryAdjust($DbQuery) { |
||
433 | |||
434 | |||
435 | protected function doUpdateWhere($table, $fieldsSet, $fieldsAdjust = array(), $where = array(), $isOneRecord = DB_RECORDS_ALL, $whereDanger = array()) { |
||
448 | |||
449 | public function doUpdateRowSet($table, $fieldsAndValues, $where) { |
||
452 | |||
453 | public function doUpdateTableSet($table, $fieldsAndValues, $where = array()) { |
||
456 | |||
457 | public function doUpdateRowAdjust($table, $fieldsSet, $fieldsAdjust, $where) { |
||
460 | |||
461 | public function doUpdateTableAdjust($table, $fieldsSet, $fieldsAdjust, $where, $whereDanger = array()) { |
||
464 | |||
465 | |||
466 | // |
||
467 | // DELETERS ---------------------------------------------------------------------------------------------------------- |
||
468 | /** |
||
469 | * @param string $table |
||
470 | * @param array $where |
||
471 | * @param bool $isOneRecord |
||
472 | * |
||
473 | * @return DbQuery |
||
474 | */ |
||
475 | protected function buildDeleteQuery($table, $where, $isOneRecord = DB_RECORDS_ALL) { |
||
482 | |||
483 | /** |
||
484 | * @param string $table |
||
485 | * @param array $where - simple WHERE statement list which can be combined with AND |
||
486 | * @param bool $isOneRecord |
||
487 | * |
||
488 | * @return array|bool|mysqli_result|null |
||
489 | */ |
||
490 | public function doDeleteWhere($table, $where, $isOneRecord = DB_RECORDS_ALL) { |
||
497 | |||
498 | /** |
||
499 | * Early deprecated function for complex delete conditions |
||
500 | * |
||
501 | * Used for malformed $where conditions |
||
502 | * Also whereDanger can contain references for other {{tables}} |
||
503 | * |
||
504 | * @param string $table |
||
505 | * @param array $where |
||
506 | * @param array $whereDanger |
||
507 | * |
||
508 | * @return array|bool|mysqli_result|null |
||
509 | * @deprecated |
||
510 | */ |
||
511 | public function doDeleteDanger($table, $where, $whereDanger) { |
||
519 | |||
520 | /** |
||
521 | * @param string $table |
||
522 | * @param array $where - simple WHERE statement list which can be combined with AND |
||
523 | * |
||
524 | * @return array|bool|mysqli_result|null |
||
525 | */ |
||
526 | public function doDeleteRow($table, $where) { |
||
529 | |||
530 | /** |
||
531 | * Perform simple delete queries on fixed tables w/o params |
||
532 | * |
||
533 | * @param string $query |
||
534 | * |
||
535 | * @return array|bool|mysqli_result|null |
||
536 | */ |
||
537 | public function doDeleteSql($query) { |
||
540 | |||
541 | |||
542 | // LOCKERS ---------------------------------------------------------------------------------------------------------- |
||
543 | /** |
||
544 | * @param DbQueryConstructor $stmt |
||
545 | * @param bool $skip_query_check |
||
546 | */ |
||
547 | public function doStmtLockAll($stmt, $skip_query_check = false) { |
||
557 | |||
558 | |||
559 | // |
||
560 | // OTHER FUNCTIONS ---------------------------------------------------------------------------------------------------------- |
||
561 | // TODO Заменить это на новый логгер |
||
562 | protected function security_watch_user_queries($query) { |
||
583 | |||
584 | |||
585 | public function security_query_check_bad_words($query) { |
||
642 | |||
643 | /** |
||
644 | * @param bool $prefixed_only |
||
645 | * |
||
646 | * @return array |
||
647 | */ |
||
648 | public function db_get_table_list($prefixed_only = true) { |
||
668 | |||
669 | /** |
||
670 | * @param string $statement |
||
671 | * |
||
672 | * @return bool|mysqli_stmt |
||
673 | */ |
||
674 | View Code Duplication | public function db_prepare($statement) { |
|
681 | |||
682 | |||
683 | /** |
||
684 | * L1 perform the query |
||
685 | * |
||
686 | * @param $query_string |
||
687 | * |
||
688 | * @return bool|mysqli_result |
||
689 | */ |
||
690 | View Code Duplication | public function db_sql_query($query_string) { |
|
697 | |||
698 | /** |
||
699 | * L1 fetch assoc array |
||
700 | * |
||
701 | * @param mysqli_result $query |
||
702 | * |
||
703 | * @return array|null |
||
704 | */ |
||
705 | View Code Duplication | public function db_fetch($query) { |
|
712 | |||
713 | public function db_fetch_row(&$query) { |
||
716 | |||
717 | public function db_escape($unescaped_string) { |
||
720 | |||
721 | public function driver_disconnect() { |
||
724 | |||
725 | public function db_error() { |
||
728 | |||
729 | public function db_insert_id() { |
||
732 | |||
733 | public function db_num_rows(&$result) { |
||
736 | |||
737 | /** |
||
738 | * @return int -1 means error |
||
739 | */ |
||
740 | public function db_affected_rows() { |
||
743 | |||
744 | /** |
||
745 | * @return string |
||
746 | */ |
||
747 | public function db_get_client_info() { |
||
750 | |||
751 | /** |
||
752 | * @return string |
||
753 | */ |
||
754 | public function db_get_server_info() { |
||
757 | |||
758 | /** |
||
759 | * @return string |
||
760 | */ |
||
761 | public function db_get_host_info() { |
||
764 | |||
765 | public function db_get_server_stat() { |
||
776 | |||
777 | /** |
||
778 | * @return array |
||
779 | * @throws Exception |
||
780 | */ |
||
781 | public function db_core_show_status() { |
||
794 | |||
795 | public function mysql_get_table_list() { |
||
798 | |||
799 | public function mysql_get_innodb_status() { |
||
802 | |||
803 | /** |
||
804 | * @return DbRowDirectOperator |
||
805 | */ |
||
806 | public function getOperator() { |
||
809 | |||
810 | |||
811 | |||
812 | // Some wrappers to DbTransaction |
||
813 | // Unused for now |
||
814 | /** |
||
815 | * @return DbTransaction |
||
816 | */ |
||
817 | public function getTransaction() { |
||
820 | |||
821 | public function transactionCheck($status = null) { |
||
824 | |||
825 | public function transactionStart($level = '') { |
||
828 | |||
829 | public function transactionCommit() { |
||
832 | |||
833 | public function transactionRollback() { |
||
836 | |||
837 | } |
||
838 |