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()) |
||
98 | |||
99 | /** |
||
100 | * Fix up the prefix so it doesn't require the database to be selected. |
||
101 | * |
||
102 | * @param string $db_prefix |
||
103 | * @param string $db_name |
||
104 | * |
||
105 | * @return string |
||
106 | */ |
||
107 | public function fix_prefix($db_prefix, $db_name) |
||
113 | |||
114 | /** |
||
115 | * Do a query. Takes care of errors too. |
||
116 | * |
||
117 | * @param string $identifier |
||
118 | * @param string $db_string |
||
119 | * @param mixed[]|false $db_values = array() |
||
120 | * @param mysqli_result|false|null $connection = null |
||
121 | * @throws Elk_Exception |
||
122 | */ |
||
123 | public function query($identifier, $db_string, $db_values = array(), $connection = null) |
||
124 | { |
||
125 | global $db_show_debug, $time_start, $modSettings; |
||
126 | |||
127 | // Comments that are allowed in a query are preg_removed. |
||
128 | static $allowed_comments_from = array( |
||
129 | '~\s+~s', |
||
130 | '~/\*!40001 SQL_NO_CACHE \*/~', |
||
131 | '~/\*!40000 USE INDEX \([A-Za-z\_]+?\) \*/~', |
||
132 | '~/\*!40100 ON DUPLICATE KEY UPDATE id_msg = \d+ \*/~', |
||
133 | ); |
||
134 | static $allowed_comments_to = array( |
||
135 | ' ', |
||
136 | '', |
||
137 | '', |
||
138 | '', |
||
139 | ); |
||
140 | |||
141 | // Decide which connection to use. |
||
142 | $connection = $connection === null ? $this->_connection : $connection; |
||
143 | |||
144 | // One more query.... |
||
145 | $this->_query_count++; |
||
146 | |||
147 | View Code Duplication | if (empty($modSettings['disableQueryCheck']) && strpos($db_string, '\'') !== false && empty($db_values['security_override'])) |
|
148 | $this->error_backtrace('Hacking attempt...', 'Illegal character (\') used in query...', true, __FILE__, __LINE__); |
||
149 | |||
150 | // Use "ORDER BY null" to prevent Mysql doing filesorts for Group By clauses without an Order By |
||
151 | if (strpos($db_string, 'GROUP BY') !== false && strpos($db_string, 'ORDER BY') === false && strpos($db_string, 'INSERT INTO') === false) |
||
152 | { |
||
153 | // Add before LIMIT |
||
154 | if ($pos = strpos($db_string, 'LIMIT ')) |
||
155 | $db_string = substr($db_string, 0, $pos) . "\t\t\tORDER BY null\n" . substr($db_string, $pos, strlen($db_string)); |
||
156 | else |
||
157 | // Append it. |
||
158 | $db_string .= "\n\t\t\tORDER BY null"; |
||
159 | } |
||
160 | |||
161 | View Code Duplication | if (empty($db_values['security_override']) && (!empty($db_values) || strpos($db_string, '{db_prefix}') !== false)) |
|
162 | { |
||
163 | // Store these values for use in the callback function. |
||
164 | $this->_db_callback_values = $db_values; |
||
165 | $this->_db_callback_connection = $connection; |
||
166 | |||
167 | // Inject the values passed to this function. |
||
168 | $db_string = preg_replace_callback('~{([a-z_]+)(?::([a-zA-Z0-9_-]+))?}~', array($this, 'replacement__callback'), $db_string); |
||
169 | |||
170 | // No need for them any longer. |
||
171 | $this->_db_callback_values = array(); |
||
172 | $this->_db_callback_connection = null; |
||
173 | } |
||
174 | |||
175 | // Debugging. |
||
176 | View Code Duplication | if ($db_show_debug === true) |
|
177 | { |
||
178 | $debug = Debug::instance(); |
||
179 | |||
180 | // Get the file and line number this function was called. |
||
181 | list ($file, $line) = $this->error_backtrace('', '', 'return', __FILE__, __LINE__); |
||
182 | |||
183 | if (!empty($_SESSION['debug_redirect'])) |
||
184 | { |
||
185 | $debug->merge_db($_SESSION['debug_redirect']); |
||
186 | // @todo this may be off by 1 |
||
187 | $this->_query_count += count($_SESSION['debug_redirect']); |
||
188 | $_SESSION['debug_redirect'] = array(); |
||
189 | } |
||
190 | |||
191 | // Don't overload it. |
||
192 | $st = microtime(true); |
||
193 | $db_cache = array(); |
||
194 | $db_cache['q'] = $this->_query_count < 50 ? $db_string : '...'; |
||
195 | $db_cache['f'] = $file; |
||
196 | $db_cache['l'] = $line; |
||
197 | $db_cache['s'] = $st - $time_start; |
||
198 | } |
||
199 | |||
200 | // First, we clean strings out of the query, reduce whitespace, lowercase, and trim - so we can check it over. |
||
201 | if (empty($modSettings['disableQueryCheck'])) |
||
202 | { |
||
203 | $clean = ''; |
||
204 | $old_pos = 0; |
||
205 | $pos = -1; |
||
206 | View Code Duplication | while (true) |
|
207 | { |
||
208 | $pos = strpos($db_string, '\'', $pos + 1); |
||
209 | if ($pos === false) |
||
210 | break; |
||
211 | $clean .= substr($db_string, $old_pos, $pos - $old_pos); |
||
212 | |||
213 | while (true) |
||
214 | { |
||
215 | $pos1 = strpos($db_string, '\'', $pos + 1); |
||
216 | $pos2 = strpos($db_string, '\\', $pos + 1); |
||
217 | if ($pos1 === false) |
||
218 | break; |
||
219 | elseif ($pos2 === false || $pos2 > $pos1) |
||
220 | { |
||
221 | $pos = $pos1; |
||
222 | break; |
||
223 | } |
||
224 | |||
225 | $pos = $pos2 + 1; |
||
226 | } |
||
227 | |||
228 | $clean .= ' %s '; |
||
229 | $old_pos = $pos + 1; |
||
230 | } |
||
231 | |||
232 | $clean .= substr($db_string, $old_pos); |
||
233 | $clean = trim(strtolower(preg_replace($allowed_comments_from, $allowed_comments_to, $clean))); |
||
234 | |||
235 | // Comments? We don't use comments in our queries, we leave 'em outside! |
||
236 | View Code Duplication | if (strpos($clean, '/*') > 2 || strpos($clean, '--') !== false || strpos($clean, ';') !== false) |
|
237 | $fail = true; |
||
238 | // Trying to change passwords, slow us down, or something? |
||
239 | elseif (strpos($clean, 'sleep') !== false && preg_match('~(^|[^a-z])sleep($|[^[_a-z])~s', $clean) != 0) |
||
240 | $fail = true; |
||
241 | elseif (strpos($clean, 'benchmark') !== false && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) |
||
242 | $fail = true; |
||
243 | |||
244 | if (!empty($fail) && function_exists('log_error')) |
||
245 | $this->error_backtrace('Hacking attempt...', 'Hacking attempt...' . "\n" . $db_string, E_USER_ERROR, __FILE__, __LINE__); |
||
246 | } |
||
247 | |||
248 | if ($this->_unbuffered === false) |
||
249 | $ret = @mysqli_query($connection, $db_string); |
||
250 | else |
||
251 | $ret = @mysqli_query($connection, $db_string, MYSQLI_USE_RESULT); |
||
252 | |||
253 | // @deprecated since 1.1 - use skip_next_error method |
||
254 | if (!empty($db_values['db_error_skip'])) |
||
255 | { |
||
256 | $this->_skip_error = true; |
||
257 | } |
||
258 | |||
259 | if ($ret === false && $this->_skip_error === false) |
||
260 | { |
||
261 | $ret = $this->error($db_string, $connection); |
||
262 | } |
||
263 | |||
264 | // Revert not to skip errors |
||
265 | if ($this->_skip_error === true) |
||
266 | { |
||
267 | $this->_skip_error = false; |
||
268 | } |
||
269 | |||
270 | // Debugging. |
||
271 | View Code Duplication | if ($db_show_debug === true) |
|
272 | { |
||
273 | $db_cache['t'] = microtime(true) - $st; |
||
274 | $debug->db_query($db_cache); |
||
275 | } |
||
276 | |||
277 | return $ret; |
||
278 | } |
||
279 | |||
280 | /** |
||
281 | * Checks if the string contains any 4byte chars and if so, |
||
282 | * converts them into HTML entities. |
||
283 | * |
||
284 | * This is necessary because MySQL utf8 doesn't know how to store such |
||
285 | * characters and would generate an error any time one is used. |
||
286 | * The 4byte chars are used by emoji |
||
287 | * |
||
288 | * @param string $string |
||
289 | * @return string |
||
290 | */ |
||
291 | private function _clean_4byte_chars($string) |
||
292 | { |
||
293 | global $modSettings; |
||
294 | |||
295 | if (!empty($modSettings['using_utf8mb4'])) |
||
296 | return $string; |
||
297 | |||
298 | $result = $string; |
||
299 | $ord = array_map('ord', str_split($string)); |
||
300 | |||
301 | // If we are in the 4-byte range |
||
302 | if (max($ord) >= 240) |
||
303 | { |
||
304 | // Byte length |
||
305 | $length = strlen($string); |
||
306 | $result = ''; |
||
307 | |||
308 | // Look for a 4byte marker |
||
309 | for ($i = 0; $i < $length; $i++) |
||
310 | { |
||
311 | // The first byte of a 4-byte character encoding starts with the bytes 0xF0-0xF4 (240 <-> 244) |
||
312 | // but look all the way to 247 for safe measure |
||
313 | $ord1 = $ord[$i]; |
||
314 | if ($ord1 >= 240 && $ord1 <= 247) |
||
315 | { |
||
316 | // Replace it with the corresponding html entity |
||
317 | $entity = $this->_uniord(chr($ord[$i]) . chr($ord[$i + 1]) . chr($ord[$i + 2]) . chr($ord[$i + 3])); |
||
318 | if ($entity === false) |
||
319 | $result .= "\xEF\xBF\xBD"; |
||
320 | else |
||
321 | $result .= '&#x' . dechex($entity) . ';'; |
||
322 | $i += 3; |
||
323 | } |
||
324 | else |
||
325 | $result .= $string[$i]; |
||
326 | } |
||
327 | } |
||
328 | |||
329 | return $result; |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * Converts a 4byte char into the corresponding HTML entity code. |
||
334 | * |
||
335 | * This function is derived from: |
||
336 | * http://www.greywyvern.com/code/php/utf8_html.phps |
||
337 | * |
||
338 | * @param string $c |
||
339 | * @return integer|false |
||
340 | */ |
||
341 | private function _uniord($c) |
||
358 | |||
359 | /** |
||
360 | * Affected rows from previous operation. |
||
361 | * |
||
362 | * @param mysqli|null $connection |
||
363 | */ |
||
364 | public function affected_rows($connection = null) |
||
365 | { |
||
366 | return mysqli_affected_rows($connection === null ? $this->_connection : $connection); |
||
367 | } |
||
368 | |||
369 | /** |
||
370 | * Last inserted id. |
||
371 | * |
||
372 | * @param string $table |
||
373 | * @param string|null $field = null |
||
374 | * @param mysqli|null $connection = null |
||
375 | */ |
||
376 | public function insert_id($table, $field = null, $connection = null) |
||
377 | { |
||
378 | // MySQL doesn't need the table or field information. |
||
379 | return mysqli_insert_id($connection === null ? $this->_connection : $connection); |
||
380 | } |
||
381 | |||
382 | /** |
||
383 | * Fetch a row from the result set given as parameter. |
||
384 | * MySQL implementation doesn't use $counter parameter. |
||
385 | * |
||
386 | * @param mysqli_result $result |
||
387 | * @param integer|bool $counter = false |
||
388 | */ |
||
389 | public function fetch_row($result, $counter = false) |
||
390 | { |
||
391 | // Just delegate to MySQL's function |
||
392 | return mysqli_fetch_row($result); |
||
393 | } |
||
394 | |||
395 | /** |
||
396 | * Free the resultset. |
||
397 | * |
||
398 | * @param mysqli_result $result |
||
399 | */ |
||
400 | public function free_result($result) |
||
401 | { |
||
402 | // Just delegate to MySQL's function |
||
403 | mysqli_free_result($result); |
||
404 | } |
||
405 | |||
406 | /** |
||
407 | * Get the number of rows in the result. |
||
408 | * |
||
409 | * @param mysqli_result $result |
||
410 | */ |
||
411 | public function num_rows($result) |
||
412 | { |
||
413 | // Simply delegate to the native function |
||
414 | return mysqli_num_rows($result); |
||
415 | } |
||
416 | |||
417 | /** |
||
418 | * Get the number of fields in the result set. |
||
419 | * |
||
420 | * @param mysqli_result $request |
||
421 | */ |
||
422 | public function num_fields($request) |
||
426 | |||
427 | /** |
||
428 | * Reset the internal result pointer. |
||
429 | * |
||
430 | * @param mysqli_result $request |
||
431 | * @param integer $counter |
||
432 | */ |
||
433 | public function data_seek($request, $counter) |
||
438 | |||
439 | /** |
||
440 | * Do a transaction. |
||
441 | * |
||
442 | * @param string $type - the step to perform (i.e. 'begin', 'commit', 'rollback') |
||
443 | * @param mysqli|null $connection = null |
||
444 | */ |
||
445 | public function db_transaction($type = 'commit', $connection = null) |
||
459 | |||
460 | /** |
||
461 | * Return last error string from the database server |
||
462 | * |
||
463 | * @param mysqli|null $connection = null |
||
464 | */ |
||
465 | public function last_error($connection = null) |
||
473 | |||
474 | /** |
||
475 | * Database error. |
||
476 | * Backtrace, log, try to fix. |
||
477 | * |
||
478 | * @param string $db_string |
||
479 | * @param mysqli|null $connection = null |
||
480 | * |
||
481 | * @return bool |
||
482 | * @throws Elk_Exception |
||
483 | */ |
||
484 | public function error($db_string, $connection = null) |
||
686 | |||
687 | /** |
||
688 | * Insert data. |
||
689 | * |
||
690 | * @param string $method - options 'replace', 'ignore', 'insert' |
||
691 | * @param string $table |
||
692 | * @param mixed[] $columns |
||
693 | * @param mixed[] $data |
||
694 | * @param mixed[] $keys |
||
695 | * @param bool $disable_trans = false |
||
696 | * @param mysqli|null $connection = null |
||
697 | * @throws Elk_Exception |
||
698 | */ |
||
699 | public function insert($method = 'replace', $table, $columns, $data, $keys, $disable_trans = false, $connection = null) |
||
700 | { |
||
701 | global $db_prefix; |
||
702 | |||
703 | $connection = $connection === null ? $this->_connection : $connection; |
||
704 | |||
705 | // With nothing to insert, simply return. |
||
706 | if (empty($data)) |
||
707 | return; |
||
708 | |||
709 | // Inserting data as a single row can be done as a single array. |
||
710 | if (!is_array($data[array_rand($data)])) |
||
711 | $data = array($data); |
||
712 | |||
713 | // Replace the prefix holder with the actual prefix. |
||
714 | $table = str_replace('{db_prefix}', $db_prefix, $table); |
||
715 | |||
716 | // Create the mold for a single row insert. |
||
717 | $insertData = '('; |
||
718 | View Code Duplication | foreach ($columns as $columnName => $type) |
|
719 | { |
||
720 | // Are we restricting the length? |
||
721 | if (strpos($type, 'string-') !== false) |
||
722 | $insertData .= sprintf('SUBSTRING({string:%1$s}, 1, ' . substr($type, 7) . '), ', $columnName); |
||
723 | else |
||
724 | $insertData .= sprintf('{%1$s:%2$s}, ', $type, $columnName); |
||
725 | } |
||
726 | $insertData = substr($insertData, 0, -2) . ')'; |
||
727 | |||
728 | // Create an array consisting of only the columns. |
||
729 | $indexed_columns = array_keys($columns); |
||
730 | |||
731 | // Here's where the variables are injected to the query. |
||
732 | $insertRows = array(); |
||
733 | foreach ($data as $dataRow) |
||
734 | { |
||
735 | $insertRows[] = $this->quote($insertData, $this->_array_combine($indexed_columns, $dataRow), $connection); |
||
736 | } |
||
737 | |||
738 | // Determine the method of insertion. |
||
739 | $queryTitle = $method === 'replace' ? 'REPLACE' : ($method == 'ignore' ? 'INSERT IGNORE' : 'INSERT'); |
||
740 | |||
741 | $skip_error = $table === $db_prefix . 'log_errors'; |
||
742 | $this->_skip_error = $skip_error; |
||
743 | // Do the insert. |
||
744 | $this->query('', ' |
||
745 | ' . $queryTitle . ' INTO ' . $table . '(`' . implode('`, `', $indexed_columns) . '`) |
||
746 | VALUES |
||
747 | ' . implode(', |
||
748 | ', $insertRows), |
||
749 | array( |
||
750 | 'security_override' => true, |
||
751 | ), |
||
752 | $connection |
||
753 | ); |
||
754 | } |
||
755 | |||
756 | /** |
||
757 | * Unescape an escaped string! |
||
758 | * |
||
759 | * @param string $string |
||
760 | */ |
||
761 | public function unescape_string($string) |
||
765 | |||
766 | /** |
||
767 | * Returns whether the database system supports ignore. |
||
768 | * |
||
769 | * @return boolean |
||
770 | */ |
||
771 | public function support_ignore() |
||
775 | |||
776 | /** |
||
777 | * Gets all the necessary INSERTs for the table named table_name. |
||
778 | * It goes in 250 row segments. |
||
779 | * |
||
780 | * @param string $tableName - the table to create the inserts for. |
||
781 | * @param bool $new_table |
||
782 | * |
||
783 | * @return string the query to insert the data back in, or an empty string if the table was empty. |
||
784 | * @throws Elk_Exception |
||
785 | */ |
||
786 | public function insert_sql($tableName, $new_table = false) |
||
854 | |||
855 | /** |
||
856 | * Dumps the schema (CREATE) for a table. |
||
857 | * |
||
858 | * @param string $tableName - the table |
||
859 | * |
||
860 | * @return string - the CREATE statement as string |
||
861 | * @throws Elk_Exception |
||
862 | */ |
||
863 | public function db_table_sql($tableName) |
||
967 | |||
968 | /** |
||
969 | * {@inheritdoc} |
||
970 | */ |
||
971 | public function db_list_tables($db_name_str = false, $filter = false) |
||
972 | { |
||
973 | global $db_name; |
||
974 | |||
975 | $db_name_str = $db_name_str === false ? $db_name : $db_name_str; |
||
976 | $db_name_str = trim($db_name_str); |
||
977 | $filter = $filter === false ? '' : ' LIKE \'' . $filter . '\''; |
||
978 | |||
979 | $request = $this->query('', ' |
||
980 | SHOW TABLES |
||
981 | FROM `{raw:db_name_str}` |
||
982 | {raw:filter}', |
||
983 | array( |
||
984 | 'db_name_str' => $db_name_str[0] == '`' ? strtr($db_name_str, array('`' => '')) : $db_name_str, |
||
985 | 'filter' => $filter, |
||
986 | ) |
||
987 | ); |
||
988 | $tables = array(); |
||
989 | while ($row = $this->fetch_row($request)) |
||
990 | { |
||
991 | $tables[] = $row[0]; |
||
992 | } |
||
993 | $this->free_result($request); |
||
994 | |||
995 | return $tables; |
||
996 | } |
||
997 | |||
998 | /** |
||
999 | * Backup $table_name to $backup_table. |
||
1000 | * |
||
1001 | * @param string $table_name |
||
1002 | * @param string $backup_table |
||
1003 | * |
||
1004 | * @return resource - the request handle to the table creation query |
||
1005 | * @throws Elk_Exception |
||
1006 | */ |
||
1007 | public function db_backup_table($table_name, $backup_table) |
||
1130 | |||
1131 | /** |
||
1132 | * Get the version number. |
||
1133 | * |
||
1134 | * @return string - the version |
||
1135 | * @throws Elk_Exception |
||
1136 | */ |
||
1137 | View Code Duplication | public function db_server_version() |
|
1149 | |||
1150 | /** |
||
1151 | * Get the name (title) of the database system. |
||
1152 | * |
||
1153 | * @return string |
||
1154 | */ |
||
1155 | public function db_title() |
||
1159 | |||
1160 | /** |
||
1161 | * Whether the database system is case sensitive. |
||
1162 | * |
||
1163 | * @return false |
||
1164 | */ |
||
1165 | public function db_case_sensitive() |
||
1169 | |||
1170 | /** |
||
1171 | * Escape string for the database input |
||
1172 | * |
||
1173 | * @param string $string |
||
1174 | */ |
||
1175 | public function escape_string($string) |
||
1176 | { |
||
1177 | $string = $this->_clean_4byte_chars($string); |
||
1178 | |||
1179 | return mysqli_real_escape_string($this->_connection, $string); |
||
1180 | } |
||
1181 | |||
1182 | /** |
||
1183 | * Fetch next result as association. |
||
1184 | * The mysql implementation simply delegates to mysqli_fetch_assoc(). |
||
1185 | * It ignores $counter parameter. |
||
1186 | * |
||
1187 | * @param mysqli_result $request |
||
1188 | * @param int|bool $counter = false |
||
1189 | */ |
||
1190 | public function fetch_assoc($request, $counter = false) |
||
1191 | { |
||
1192 | return mysqli_fetch_assoc($request); |
||
1193 | } |
||
1194 | |||
1195 | /** |
||
1196 | * Return server info. |
||
1197 | * |
||
1198 | * @param mysqli|null $connection |
||
1199 | * |
||
1200 | * @return string |
||
1201 | */ |
||
1202 | public function db_server_info($connection = null) |
||
1209 | |||
1210 | /** |
||
1211 | * Get the version number. |
||
1212 | * |
||
1213 | * @return string - the version |
||
1214 | * @throws Elk_Exception |
||
1215 | */ |
||
1216 | View Code Duplication | public function db_client_version() |
|
1228 | |||
1229 | /** |
||
1230 | * Select database. |
||
1231 | * |
||
1232 | * @param string|null $dbName = null |
||
1233 | * @param mysqli|null $connection = null |
||
1234 | */ |
||
1235 | public function select_db($dbName = null, $connection = null) |
||
1242 | |||
1243 | /** |
||
1244 | * Returns a reference to the existing instance |
||
1245 | */ |
||
1246 | public static function db() |
||
1247 | { |
||
1248 | return self::$_db; |
||
1249 | } |
||
1250 | |||
1251 | /** |
||
1252 | * Finds out if the connection is still valid. |
||
1253 | * |
||
1254 | * @param mysqli|null $connection = null |
||
1255 | */ |
||
1256 | public function validConnection($connection = null) |
||
1260 | } |
||
1261 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.