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 Database_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 Database_MySQL, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
28 | class Database_MySQL extends Database_Abstract |
||
29 | { |
||
30 | /** |
||
31 | * Holds current instance of the class |
||
32 | * |
||
33 | * @var Database_MySQL |
||
34 | */ |
||
35 | private static $_db = null; |
||
36 | |||
37 | /** |
||
38 | * Initializes a database connection. |
||
39 | * It returns the connection, if successful. |
||
40 | * |
||
41 | * @param string $db_server |
||
42 | * @param string $db_name |
||
43 | * @param string $db_user |
||
44 | * @param string $db_passwd |
||
45 | * @param string $db_prefix |
||
46 | * @param mixed[] $db_options |
||
47 | * |
||
48 | * @return mysqli|null |
||
49 | * @throws Elk_Exception |
||
50 | */ |
||
51 | public static function initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $db_options = array()) |
||
105 | |||
106 | /** |
||
107 | * Fix up the prefix so it doesn't require the database to be selected. |
||
108 | * |
||
109 | * @param string $db_prefix |
||
110 | * @param string $db_name |
||
111 | * |
||
112 | * @return string |
||
113 | */ |
||
114 | public function fix_prefix($db_prefix, $db_name) |
||
120 | |||
121 | /** |
||
122 | * Do a query. Takes care of errors too. |
||
123 | * |
||
124 | * @param string $identifier |
||
125 | * @param string $db_string |
||
126 | * @param mixed[]|false $db_values = array() |
||
127 | * @param mysqli_result|false|null $connection = null |
||
128 | * @throws Elk_Exception |
||
129 | */ |
||
130 | public function query($identifier, $db_string, $db_values = array(), $connection = null) |
||
131 | { |
||
132 | global $db_show_debug, $time_start, $modSettings; |
||
133 | |||
134 | // Comments that are allowed in a query are preg_removed. |
||
135 | static $allowed_comments_from = array( |
||
136 | '~\s+~s', |
||
137 | '~/\*!40001 SQL_NO_CACHE \*/~', |
||
138 | '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~', |
||
139 | '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~', |
||
140 | ); |
||
141 | static $allowed_comments_to = array( |
||
142 | ' ', |
||
143 | '', |
||
144 | '', |
||
145 | '', |
||
146 | ); |
||
147 | |||
148 | // Decide which connection to use. |
||
149 | $connection = $connection === null ? $this->_connection : $connection; |
||
150 | |||
151 | // One more query.... |
||
152 | $this->_query_count++; |
||
153 | |||
154 | View Code Duplication | if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) |
|
155 | $this->error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__); |
||
156 | |||
157 | // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By |
||
158 | if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false) |
||
159 | { |
||
160 | // Add before LIMIT |
||
161 | if ($pos = strpos($db_string, 'LIMIT ')) |
||
162 | $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string)); |
||
163 | else |
||
164 | // Append it. |
||
165 | $db_string .= "\n\t\t\tORDER BY null"; |
||
166 | } |
||
167 | |||
168 | View Code Duplication | if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) |
|
169 | { |
||
170 | // Store these values for use in the callback function. |
||
171 | $this->_db_callback_values = $db_values; |
||
172 | $this->_db_callback_connection = $connection; |
||
173 | |||
174 | // Inject the values passed to this function. |
||
175 | $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string); |
||
176 | |||
177 | // No need for them any longer. |
||
178 | $this->_db_callback_values = array(); |
||
179 | $this->_db_callback_connection = null; |
||
180 | } |
||
181 | |||
182 | // Debugging. |
||
183 | View Code Duplication | if ($db_show_debug === true) |
|
184 | { |
||
185 | $debug = Debug::instance(); |
||
186 | |||
187 | // Get the file and line number this function was called. |
||
188 | list ($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__); |
||
189 | |||
190 | if (!empty($_SESSION['debug_redirect'])) |
||
191 | { |
||
192 | $debug->merge_db($_SESSION['debug_redirect']); |
||
193 | // @todo this may be off by 1 |
||
194 | $this->_query_count += count($_SESSION['debug_redirect']); |
||
195 | $_SESSION['debug_redirect'] = array(); |
||
196 | } |
||
197 | |||
198 | // Don't overload it. |
||
199 | $st = microtime(true); |
||
200 | $db_cache = array(); |
||
201 | $db_cache['q'] = $this->_query_count < 50 ? $db_string : '...'; |
||
202 | $db_cache['f'] = $file; |
||
203 | $db_cache['l'] = $line; |
||
204 | $db_cache['s'] = $st - $time_start; |
||
205 | } |
||
206 | |||
207 | // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over. |
||
208 | if (empty($modSettings['disableQueryCheck'])) |
||
209 | { |
||
210 | $clean = ''; |
||
211 | $old_pos = 0; |
||
212 | $pos = -1; |
||
213 | View Code Duplication | while (true) |
|
214 | { |
||
215 | $pos = strpos($db_string, '\'', $pos + 1); |
||
216 | if ($pos === false) |
||
217 | break; |
||
218 | $clean .= substr($db_string, $old_pos, $pos - $old_pos); |
||
219 | |||
220 | while (true) |
||
221 | { |
||
222 | $pos1 = strpos($db_string, '\'', $pos + 1); |
||
223 | $pos2 = strpos($db_string, '\\', $pos + 1); |
||
224 | if ($pos1 === false) |
||
225 | break; |
||
226 | elseif ($pos2 === false || $pos2 > $pos1) |
||
227 | { |
||
228 | $pos = $pos1; |
||
229 | break; |
||
230 | } |
||
231 | |||
232 | $pos = $pos2 + 1; |
||
233 | } |
||
234 | |||
235 | $clean .= ' %s '; |
||
236 | $old_pos = $pos + 1; |
||
237 | } |
||
238 | |||
239 | $clean .= substr($db_string, $old_pos); |
||
240 | $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean))); |
||
241 | |||
242 | // Comments? We don't use comments in our queries, we leave 'em outside! |
||
243 | View Code Duplication | if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) |
|
244 | $fail = true; |
||
245 | // Trying to change passwords, slow us down, or something? |
||
246 | elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) |
||
247 | $fail = true; |
||
248 | elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) |
||
249 | $fail = true; |
||
250 | |||
251 | if (!empty($fail) && function_exists('log_error')) |
||
252 | $this->error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__); |
||
253 | } |
||
254 | |||
255 | if ($this->_unbuffered === false) |
||
256 | $ret = @mysqli_query($connection, $db_string); |
||
257 | else |
||
258 | $ret = @mysqli_query($connection, $db_string, MYSQLI_USE_RESULT); |
||
259 | |||
260 | // @deprecated since 1.1 - use skip_next_error method |
||
261 | if (!empty($db_values['db_error_skip'])) |
||
262 | { |
||
263 | $this->_skip_error = true; |
||
264 | } |
||
265 | |||
266 | if ($ret === false && $this->_skip_error === false) |
||
267 | { |
||
268 | $ret = $this->error($db_string, $connection); |
||
269 | } |
||
270 | |||
271 | // Revert not to skip errors |
||
272 | if ($this->_skip_error === true) |
||
273 | { |
||
274 | $this->_skip_error = false; |
||
275 | } |
||
276 | |||
277 | // Debugging. |
||
278 | View Code Duplication | if ($db_show_debug === true) |
|
279 | { |
||
280 | $db_cache['t'] = microtime(true) - $st; |
||
281 | $debug->db_query($db_cache); |
||
282 | } |
||
283 | |||
284 | return $ret; |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Checks if the string contains any 4byte chars and if so, |
||
289 | * converts them into HTML entities. |
||
290 | * |
||
291 | * This is necessary because MySQL utf8 doesn't know how to store such |
||
292 | * characters and would generate an error any time one is used. |
||
293 | * The 4byte chars are used by emoji |
||
294 | * |
||
295 | * @param string $string |
||
296 | * @return string |
||
297 | */ |
||
298 | private function _clean_4byte_chars($string) |
||
299 | { |
||
300 | global $modSettings; |
||
301 | |||
302 | if (!empty($modSettings['using_utf8mb4'])) |
||
303 | return $string; |
||
304 | |||
305 | $result = $string; |
||
306 | $ord = array_map('ord', str_split($string)); |
||
307 | |||
308 | // If we are in the 4-byte range |
||
309 | if (max($ord) >= 240) |
||
310 | { |
||
311 | // Byte length |
||
312 | $length = strlen($string); |
||
313 | $result = ''; |
||
314 | |||
315 | // Look for a 4byte marker |
||
316 | for ($i = 0; $i < $length; $i++) |
||
317 | { |
||
318 | // The first byte of a 4-byte character encoding starts with the bytes 0xF0-0xF4 (240 <-> 244) |
||
319 | // but look all the way to 247 for safe measure |
||
320 | $ord1 = $ord[$i]; |
||
321 | if ($ord1 >= 240 && $ord1 <= 247) |
||
322 | { |
||
323 | // Replace it with the corresponding html entity |
||
324 | $entity = $this->_uniord(chr($ord[$i]) . chr($ord[$i + 1]) . chr($ord[$i + 2]) . chr($ord[$i + 3])); |
||
325 | if ($entity === false) |
||
326 | $result .= "\xEF\xBF\xBD"; |
||
327 | else |
||
328 | $result .= '&#x' . dechex($entity) . ';'; |
||
329 | $i += 3; |
||
330 | } |
||
331 | else |
||
332 | $result .= $string[$i]; |
||
333 | } |
||
334 | } |
||
335 | |||
336 | return $result; |
||
337 | } |
||
338 | |||
339 | /** |
||
340 | * Converts a 4byte char into the corresponding HTML entity code. |
||
341 | * |
||
342 | * This function is derived from: |
||
343 | * http://www.greywyvern.com/code/php/utf8_html.phps |
||
344 | * |
||
345 | * @param string $c |
||
346 | * @return integer|false |
||
347 | */ |
||
348 | private function _uniord($c) |
||
365 | |||
366 | /** |
||
367 | * Affected rows from previous operation. |
||
368 | * |
||
369 | * @param mysqli|null $connection |
||
370 | */ |
||
371 | public function affected_rows($connection = null) |
||
372 | { |
||
373 | return mysqli_affected_rows($connection === null ? $this->_connection : $connection); |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Last inserted id. |
||
378 | * |
||
379 | * @param string $table |
||
380 | * @param string|null $field = null |
||
381 | * @param mysqli|null $connection = null |
||
382 | */ |
||
383 | public function insert_id($table, $field = null, $connection = null) |
||
384 | { |
||
385 | // MySQL doesn't need the table or field information. |
||
386 | return mysqli_insert_id($connection === null ? $this->_connection : $connection); |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Fetch a row from the result set given as parameter. |
||
391 | * MySQL implementation doesn't use $counter parameter. |
||
392 | * |
||
393 | * @param mysqli_result $result |
||
394 | * @param integer|bool $counter = false |
||
395 | */ |
||
396 | public function fetch_row($result, $counter = false) |
||
397 | { |
||
398 | // Just delegate to MySQL's function |
||
399 | return mysqli_fetch_row($result); |
||
400 | } |
||
401 | |||
402 | /** |
||
403 | * Free the resultset. |
||
404 | * |
||
405 | * @param mysqli_result $result |
||
406 | */ |
||
407 | public function free_result($result) |
||
408 | { |
||
409 | // Just delegate to MySQL's function |
||
410 | mysqli_free_result($result); |
||
411 | } |
||
412 | |||
413 | /** |
||
414 | * Get the number of rows in the result. |
||
415 | * |
||
416 | * @param mysqli_result $result |
||
417 | */ |
||
418 | public function num_rows($result) |
||
419 | { |
||
420 | // Simply delegate to the native function |
||
421 | return mysqli_num_rows($result); |
||
422 | } |
||
423 | |||
424 | /** |
||
425 | * Get the number of fields in the result set. |
||
426 | * |
||
427 | * @param mysqli_result $request |
||
428 | */ |
||
429 | public function num_fields($request) |
||
433 | |||
434 | /** |
||
435 | * Reset the internal result pointer. |
||
436 | * |
||
437 | * @param mysqli_result $request |
||
438 | * @param integer $counter |
||
439 | */ |
||
440 | public function data_seek($request, $counter) |
||
445 | |||
446 | /** |
||
447 | * Do a transaction. |
||
448 | * |
||
449 | * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback') |
||
450 | * @param mysqli|null $connection = null |
||
451 | */ |
||
452 | public function db_transaction($type = 'commit', $connection = null) |
||
466 | |||
467 | /** |
||
468 | * Return last error string from the database server |
||
469 | * |
||
470 | * @param mysqli|null $connection = null |
||
471 | */ |
||
472 | public function last_error($connection = null) |
||
480 | |||
481 | /** |
||
482 | * Database error. |
||
483 | * Backtrace, log, try to fix. |
||
484 | * |
||
485 | * @param string $db_string |
||
486 | * @param mysqli|null $connection = null |
||
487 | * |
||
488 | * @return bool |
||
489 | * @throws Elk_Exception |
||
490 | */ |
||
491 | public function error($db_string, $connection = null) |
||
693 | |||
694 | /** |
||
695 | * Insert data. |
||
696 | * |
||
697 | * @param string $method - options 'replace', 'ignore', 'insert' |
||
698 | * @param string $table |
||
699 | * @param mixed[] $columns |
||
700 | * @param mixed[] $data |
||
701 | * @param mixed[] $keys |
||
702 | * @param bool $disable_trans = false |
||
703 | * @param mysqli|null $connection = null |
||
704 | * @throws Elk_Exception |
||
705 | */ |
||
706 | public function insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) |
||
707 | { |
||
708 | global $db_prefix; |
||
709 | |||
710 | $connection = $connection === null ? $this->_connection : $connection; |
||
711 | |||
712 | // With nothing to insert, simply return. |
||
713 | if (empty($data)) |
||
714 | return; |
||
715 | |||
716 | // Inserting data as a single row can be done as a single array. |
||
717 | if (!is_array($data[array_rand($data)])) |
||
718 | $data = array($data); |
||
719 | |||
720 | // Replace the prefix holder with the actual prefix. |
||
721 | $table = str_replace('{db_prefix}', $db_prefix, $table); |
||
722 | |||
723 | // Create the mold for a single row insert. |
||
724 | $insertData = '('; |
||
725 | View Code Duplication | foreach ($columns as $columnName => $type) |
|
726 | { |
||
727 | // Are we restricting the length? |
||
728 | if (strpos($type, 'string-') !== false) |
||
729 | $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName); |
||
730 | else |
||
731 | $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName); |
||
732 | } |
||
733 | $insertData = substr($insertData, 0, -2) . ')'; |
||
734 | |||
735 | // Create an array consisting of only the columns. |
||
736 | $indexed_columns = array_keys($columns); |
||
737 | |||
738 | // Here's where the variables are injected to the query. |
||
739 | $insertRows = array(); |
||
740 | foreach ($data as $dataRow) |
||
741 | { |
||
742 | $insertRows[] = $this->quote($insertData, $this->_array_combine($indexed_columns, $dataRow), $connection); |
||
743 | } |
||
744 | |||
745 | // Determine the method of insertion. |
||
746 | $queryTitle = $method === 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT'); |
||
747 | |||
748 | $skip_error = $table === $db_prefix . 'log_errors'; |
||
749 | $this->_skip_error = $skip_error; |
||
750 | // Do the insert. |
||
751 | $this->query('', ' |
||
752 | ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`) |
||
753 | VALUES |
||
754 | ' . implode(', |
||
755 | ', $insertRows), |
||
756 | array( |
||
757 | 'security_override' => true, |
||
758 | ), |
||
759 | $connection |
||
760 | ); |
||
761 | } |
||
762 | |||
763 | /** |
||
764 | * Unescape an escaped string! |
||
765 | * |
||
766 | * @param string $string |
||
767 | */ |
||
768 | public function unescape_string($string) |
||
772 | |||
773 | /** |
||
774 | * Returns whether the database system supports ignore. |
||
775 | * |
||
776 | * @return boolean |
||
777 | */ |
||
778 | public function support_ignore() |
||
782 | |||
783 | /** |
||
784 | * Gets all the necessary INSERTs for the table named table_name. |
||
785 | * It goes in 250 row segments. |
||
786 | * |
||
787 | * @param string $tableName - the table to create the inserts for. |
||
788 | * @param bool $new_table |
||
789 | * |
||
790 | * @return string the query to insert the data back in, or an empty string if the table was empty. |
||
791 | * @throws Elk_Exception |
||
792 | */ |
||
793 | public function insert_sql($tableName, $new_table = false) |
||
861 | |||
862 | /** |
||
863 | * Dumps the schema (CREATE) for a table. |
||
864 | * |
||
865 | * @param string $tableName - the table |
||
866 | * |
||
867 | * @return string - the CREATE statement as string |
||
868 | * @throws Elk_Exception |
||
869 | */ |
||
870 | public function db_table_sql($tableName) |
||
974 | |||
975 | /** |
||
976 | * {@inheritdoc} |
||
977 | */ |
||
978 | public function db_list_tables($db_name_str = false, $filter = false) |
||
979 | { |
||
980 | global $db_name; |
||
981 | |||
982 | $db_name_str = $db_name_str === false ? $db_name : $db_name_str; |
||
983 | $db_name_str = trim($db_name_str); |
||
984 | $filter = $filter === false ? '' : ' LIKE \'' . $filter . '\''; |
||
985 | |||
986 | $request = $this->query('', ' |
||
987 | SHOW TABLES |
||
988 | FROM `{raw:db_name_str}` |
||
989 | {raw:filter}', |
||
990 | array( |
||
991 | 'db_name_str' => $db_name_str[0] == '`' ? strtr($db_name_str, array('`' => '')) : $db_name_str, |
||
992 | 'filter' => $filter, |
||
993 | ) |
||
994 | ); |
||
995 | $tables = array(); |
||
996 | while ($row = $this->fetch_row($request)) |
||
997 | { |
||
998 | $tables[] = $row[0]; |
||
999 | } |
||
1000 | $this->free_result($request); |
||
1001 | |||
1002 | return $tables; |
||
1003 | } |
||
1004 | |||
1005 | /** |
||
1006 | * Backup $table_name to $backup_table. |
||
1007 | * |
||
1008 | * @param string $table_name |
||
1009 | * @param string $backup_table |
||
1010 | * |
||
1011 | * @return resource - the request handle to the table creation query |
||
1012 | * @throws Elk_Exception |
||
1013 | */ |
||
1014 | public function db_backup_table($table_name, $backup_table) |
||
1137 | |||
1138 | /** |
||
1139 | * Get the version number. |
||
1140 | * |
||
1141 | * @return string - the version |
||
1142 | * @throws Elk_Exception |
||
1143 | */ |
||
1144 | View Code Duplication | public function db_server_version() |
|
1156 | |||
1157 | /** |
||
1158 | * Get the name (title) of the database system. |
||
1159 | * |
||
1160 | * @return string |
||
1161 | */ |
||
1162 | public function db_title() |
||
1166 | |||
1167 | /** |
||
1168 | * Whether the database system is case sensitive. |
||
1169 | * |
||
1170 | * @return false |
||
1171 | */ |
||
1172 | public function db_case_sensitive() |
||
1176 | |||
1177 | /** |
||
1178 | * Escape string for the database input |
||
1179 | * |
||
1180 | * @param string $string |
||
1181 | */ |
||
1182 | public function escape_string($string) |
||
1183 | { |
||
1184 | $string = $this->_clean_4byte_chars($string); |
||
1185 | |||
1186 | return mysqli_real_escape_string($this->_connection, $string); |
||
1187 | } |
||
1188 | |||
1189 | /** |
||
1190 | * Fetch next result as association. |
||
1191 | * The mysql implementation simply delegates to mysqli_fetch_assoc(). |
||
1192 | * It ignores $counter parameter. |
||
1193 | * |
||
1194 | * @param mysqli_result $request |
||
1195 | * @param int|bool $counter = false |
||
1196 | */ |
||
1197 | public function fetch_assoc($request, $counter = false) |
||
1198 | { |
||
1199 | return mysqli_fetch_assoc($request); |
||
1200 | } |
||
1201 | |||
1202 | /** |
||
1203 | * Return server info. |
||
1204 | * |
||
1205 | * @param mysqli|null $connection |
||
1206 | * |
||
1207 | * @return string |
||
1208 | */ |
||
1209 | public function db_server_info($connection = null) |
||
1216 | |||
1217 | /** |
||
1218 | * Get the version number. |
||
1219 | * |
||
1220 | * @return string - the version |
||
1221 | * @throws Elk_Exception |
||
1222 | */ |
||
1223 | View Code Duplication | public function db_client_version() |
|
1235 | |||
1236 | /** |
||
1237 | * Select database. |
||
1238 | * |
||
1239 | * @param string|null $dbName = null |
||
1240 | * @param mysqli|null $connection = null |
||
1241 | */ |
||
1242 | public function select_db($dbName = null, $connection = null) |
||
1249 | |||
1250 | /** |
||
1251 | * Returns a reference to the existing instance |
||
1252 | */ |
||
1253 | public static function db() |
||
1254 | { |
||
1255 | return self::$_db; |
||
1256 | } |
||
1257 | |||
1258 | /** |
||
1259 | * Finds out if the connection is still valid. |
||
1260 | * |
||
1261 | * @param mysqli|null $connection = null |
||
1262 | */ |
||
1263 | public function validConnection($connection = null) |
||
1267 | } |
||
1268 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.