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 DbMySQLOld 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 DbMySQLOld, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
29 | class DbMySQLOld extends DbBase implements DbBaseInterface |
||
30 | { |
||
31 | |||
32 | /** |
||
33 | * Resource de la Conexión a MySQL |
||
34 | * |
||
35 | * @var resource |
||
36 | */ |
||
37 | public $id_connection; |
||
38 | /** |
||
39 | * Último Resultado de una Query |
||
40 | * |
||
41 | * @var resource |
||
42 | */ |
||
43 | public $last_result_query; |
||
44 | /** |
||
45 | * Última sentencia SQL enviada a MySQL |
||
46 | * |
||
47 | * @var string |
||
48 | */ |
||
49 | protected $last_query; |
||
50 | /** |
||
51 | * Último error generado por MySQL |
||
52 | * |
||
53 | * @var string |
||
54 | */ |
||
55 | public $last_error; |
||
56 | |||
57 | /** |
||
58 | * Resultado de Array Asociativo |
||
59 | * |
||
60 | */ |
||
61 | const DB_ASSOC = MYSQL_ASSOC; |
||
62 | |||
63 | /** |
||
64 | * Resultado de Array Asociativo y Númerico |
||
65 | * |
||
66 | */ |
||
67 | const DB_BOTH = MYSQL_BOTH; |
||
68 | |||
69 | /** |
||
70 | * Resultado de Array Númerico |
||
71 | * |
||
72 | */ |
||
73 | const DB_NUM = MYSQL_NUM; |
||
74 | |||
75 | /** |
||
76 | * Tipo de Dato Integer |
||
77 | * |
||
78 | */ |
||
79 | const TYPE_INTEGER = 'INTEGER'; |
||
80 | |||
81 | /** |
||
82 | * Tipo de Dato Date |
||
83 | * |
||
84 | */ |
||
85 | const TYPE_DATE = 'DATE'; |
||
86 | |||
87 | /** |
||
88 | * Tipo de Dato Varchar |
||
89 | * |
||
90 | */ |
||
91 | const TYPE_VARCHAR = 'VARCHAR'; |
||
92 | |||
93 | /** |
||
94 | * Tipo de Dato Decimal |
||
95 | * |
||
96 | */ |
||
97 | const TYPE_DECIMAL = 'DECIMAL'; |
||
98 | |||
99 | /** |
||
100 | * Tipo de Dato Datetime |
||
101 | * |
||
102 | */ |
||
103 | const TYPE_DATETIME = 'DATETIME'; |
||
104 | |||
105 | /** |
||
106 | * Tipo de Dato Char |
||
107 | * |
||
108 | */ |
||
109 | const TYPE_CHAR = 'CHAR'; |
||
110 | |||
111 | /** |
||
112 | * Hace una conexión a la base de datos de MySQL |
||
113 | * |
||
114 | * @param array $config |
||
115 | * @return bool |
||
116 | */ |
||
117 | public function connect($config) |
||
118 | { |
||
119 | |||
120 | if (!extension_loaded('mysql')) { |
||
121 | throw new KumbiaException('Debe cargar la extensión de PHP llamada php_mysql'); |
||
122 | } |
||
123 | if (!isset($config['port']) || !$config['port']) $config['port'] = 3306; |
||
124 | |||
125 | if ($this->id_connection = mysql_connect("{$config['host']}:{$config['port']}", $config['username'], $config['password'], true)) { |
||
126 | if ($config['name'] !== '') { |
||
127 | if (!mysql_select_db($config['name'], $this->id_connection)) { |
||
128 | throw new KumbiaException($this->error()); |
||
129 | } |
||
130 | } |
||
131 | //Selecciona charset |
||
132 | if (isset($config['charset'])) mysql_query("SET NAMES {$config['charset']}"); |
||
133 | //mysql_set_charset($config['charset'],$this->id_connection); //Necesita mysql > 5.0.7 |
||
134 | return true; |
||
135 | } else { |
||
136 | throw new KumbiaException($this->error()); |
||
137 | } |
||
138 | } |
||
139 | |||
140 | /** |
||
141 | * Efectua operaciones SQL sobre la base de datos |
||
142 | * |
||
143 | * @param string $sql_query |
||
144 | * @return resource or false |
||
145 | */ |
||
146 | public function query($sql_query) |
||
147 | { |
||
148 | $this->debug($sql_query); |
||
149 | if ($this->logger) { |
||
150 | Logger::debug($sql_query); |
||
151 | } |
||
152 | |||
153 | $this->last_query = $sql_query; |
||
154 | if ($result_query = mysql_query($sql_query, $this->id_connection)) { |
||
155 | $this->last_result_query = $result_query; |
||
156 | return $result_query; |
||
157 | } else { |
||
158 | throw new KumbiaException($this->error(" al ejecutar <em>\"$sql_query\"</em>")); |
||
159 | } |
||
160 | } |
||
161 | |||
162 | /** |
||
163 | * Cierra la Conexión al Motor de Base de datos |
||
164 | */ |
||
165 | public function close() |
||
166 | { |
||
167 | if ($this->id_connection) { |
||
168 | return mysql_close(); |
||
169 | } |
||
170 | return false; |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * Devuelve fila por fila el contenido de un select |
||
175 | * |
||
176 | * @param resource $result_query |
||
177 | * @param int $opt |
||
178 | * @return array |
||
179 | */ |
||
180 | public function fetch_array($result_query='', $opt=MYSQL_BOTH) |
||
181 | { |
||
182 | |||
183 | if (!$result_query) { |
||
184 | $result_query = $this->last_result_query; |
||
185 | if (!$result_query) { |
||
186 | return false; |
||
187 | } |
||
188 | } |
||
189 | return mysql_fetch_array($result_query, $opt); |
||
190 | } |
||
191 | |||
192 | /** |
||
193 | * Constructor de la Clase |
||
194 | * |
||
195 | * @param array $config |
||
196 | */ |
||
197 | public function __construct($config) |
||
198 | { |
||
199 | $this->connect($config); |
||
200 | } |
||
201 | |||
202 | /** |
||
203 | * Devuelve el numero de filas de un select |
||
204 | */ |
||
205 | public function num_rows($result_query='') |
||
206 | { |
||
207 | |||
208 | if (!$result_query) { |
||
209 | $result_query = $this->last_result_query; |
||
210 | if (!$result_query) { |
||
211 | return false; |
||
212 | } |
||
213 | } |
||
214 | if (($number_rows = mysql_num_rows($result_query)) !== false) { |
||
215 | return $number_rows; |
||
216 | } else { |
||
217 | throw new KumbiaException($this->error()); |
||
218 | } |
||
219 | } |
||
220 | |||
221 | /** |
||
222 | * Devuelve el nombre de un campo en el resultado de un select |
||
223 | * |
||
224 | * @param int $number |
||
225 | * @param resource $result_query |
||
226 | * @return string |
||
227 | */ |
||
228 | public function field_name($number, $result_query='') |
||
229 | { |
||
230 | |||
231 | if (!$result_query) { |
||
232 | $result_query = $this->last_result_query; |
||
233 | if (!$result_query) { |
||
234 | return false; |
||
235 | } |
||
236 | } |
||
237 | if (($fieldName = mysql_field_name($result_query, $number)) !== false) { |
||
238 | return $fieldName; |
||
239 | } else { |
||
240 | throw new KumbiaException($this->error()); |
||
241 | } |
||
242 | } |
||
243 | |||
244 | /** |
||
245 | * Se Mueve al resultado indicado por $number en un select |
||
246 | * |
||
247 | * @param int $number |
||
248 | * @param resource $result_query |
||
249 | * @return boolean |
||
250 | */ |
||
251 | public function data_seek($number, $result_query='') |
||
252 | { |
||
253 | if (!$result_query) { |
||
254 | $result_query = $this->last_result_query; |
||
255 | if (!$result_query) { |
||
256 | return false; |
||
257 | } |
||
258 | } |
||
259 | if (($success = mysql_data_seek($result_query, $number)) !== false) { |
||
260 | return $success; |
||
261 | } else { |
||
262 | throw new KumbiaException($this->error()); |
||
263 | } |
||
264 | } |
||
265 | |||
266 | /** |
||
267 | * Numero de Filas afectadas en un insert, update o delete |
||
268 | * |
||
269 | * @param resource $result_query |
||
270 | * @return int |
||
271 | */ |
||
272 | public function affected_rows($result_query='') |
||
273 | { |
||
274 | if (($numberRows = mysql_affected_rows()) !== false) { |
||
275 | return $numberRows; |
||
276 | } else { |
||
277 | throw new KumbiaException($this->error()); |
||
278 | } |
||
279 | } |
||
280 | |||
281 | /** |
||
282 | * Devuelve el error de MySQL |
||
283 | * |
||
284 | * @return string |
||
285 | */ |
||
286 | public function error($err='') |
||
287 | { |
||
288 | if (!$this->id_connection) { |
||
289 | $this->last_error = mysql_error() ? mysql_error() : "[Error Desconocido en MySQL: $err]"; |
||
290 | if ($this->logger) { |
||
291 | Logger::error($this->last_error); |
||
292 | } |
||
293 | return $this->last_error; |
||
294 | } |
||
295 | $this->last_error = mysql_error() ? mysql_error() : "[Error Desconocido en MySQL: $err]"; |
||
296 | $this->last_error.= $err; |
||
297 | if ($this->logger) { |
||
298 | Logger::error($this->last_error); |
||
299 | } |
||
300 | return $this->last_error; |
||
301 | } |
||
302 | |||
303 | /** |
||
304 | * Devuelve el no error de MySQL |
||
305 | * |
||
306 | * @return int |
||
307 | */ |
||
308 | public function no_error() |
||
309 | { |
||
310 | return mysql_errno(); |
||
311 | } |
||
312 | |||
313 | /** |
||
314 | * Devuelve el ultimo id autonumerico generado en la BD |
||
315 | * |
||
316 | * @return int |
||
317 | */ |
||
318 | public function last_insert_id($table='', $primary_key='') |
||
319 | { |
||
320 | return mysql_insert_id($this->id_connection); |
||
321 | } |
||
322 | |||
323 | /** |
||
324 | * Verifica si una tabla existe o no |
||
325 | * |
||
326 | * @param string $table |
||
327 | * @return boolean |
||
328 | */ |
||
329 | public function table_exists($table, $schema='') |
||
330 | { |
||
331 | $table = addslashes("$table"); |
||
332 | if ($schema == '') { |
||
333 | $num = $this->fetch_one("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'"); |
||
334 | } else { |
||
335 | $schema = addslashes("$schema"); |
||
336 | $num = $this->fetch_one("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table' AND TABLE_SCHEMA = '$schema'"); |
||
337 | } |
||
338 | return $num[0]; |
||
339 | } |
||
340 | |||
341 | /** |
||
342 | * Devuelve un LIMIT valido para un SELECT del RBDM |
||
343 | * |
||
344 | * @param string $sql consulta sql |
||
345 | * @return string |
||
346 | */ |
||
347 | public function limit($sql) |
||
348 | { |
||
349 | $params = Util::getParams(func_get_args()); |
||
350 | $sql_new = $sql; |
||
351 | |||
352 | if (isset($params['limit']) && is_numeric($params['limit'])) { |
||
353 | $sql_new.=" LIMIT $params[limit]"; |
||
354 | } |
||
355 | |||
356 | if (isset($params['offset']) && is_numeric($params['offset'])) { |
||
357 | $sql_new.=" OFFSET $params[offset]"; |
||
358 | } |
||
359 | |||
360 | return $sql_new; |
||
361 | } |
||
362 | |||
363 | /** |
||
364 | * Borra una tabla de la base de datos |
||
365 | * |
||
366 | * @param string $table |
||
367 | * @return boolean |
||
368 | */ |
||
369 | public function drop_table($table, $if_exists=true) |
||
370 | { |
||
371 | if ($if_exists) { |
||
372 | return $this->query("DROP TABLE IF EXISTS $table"); |
||
373 | } else { |
||
374 | return $this->query("DROP TABLE $table"); |
||
375 | } |
||
376 | } |
||
377 | |||
378 | /** |
||
379 | * Crea una tabla utilizando SQL nativo del RDBM |
||
380 | * |
||
381 | * TODO: |
||
382 | * - Falta que el parametro index funcione. Este debe listar indices compuestos multipes y unicos |
||
383 | * - Agregar el tipo de tabla que debe usarse (MySQL) |
||
384 | * - Soporte para campos autonumericos |
||
385 | * - Soporte para llaves foraneas |
||
386 | * |
||
387 | * @param string $table |
||
388 | * @param array $definition |
||
389 | * @return boolean |
||
390 | */ |
||
391 | public function create_table($table, $definition, $index=array()) |
||
392 | { |
||
393 | $create_sql = "CREATE TABLE $table ("; |
||
394 | if (!is_array($definition)) { |
||
395 | throw new KumbiaException("Definición invalida para crear la tabla '$table'"); |
||
396 | } |
||
397 | $create_lines = array(); |
||
398 | $index = array(); |
||
399 | $unique_index = array(); |
||
400 | $primary = array(); |
||
401 | //$not_null = ""; |
||
402 | //$size = ""; |
||
403 | foreach ($definition as $field => $field_def) { |
||
404 | if (isset($field_def['not_null'])) { |
||
405 | $not_null = $field_def['not_null'] ? 'NOT NULL' : ''; |
||
406 | } else { |
||
407 | $not_null = ""; |
||
408 | } |
||
409 | if (isset($field_def['size'])) { |
||
410 | $size = $field_def['size'] ? '(' . $field_def['size'] . ')' : ''; |
||
411 | } else { |
||
412 | $size = ""; |
||
413 | } |
||
414 | if (isset($field_def['index'])) { |
||
415 | if ($field_def['index']) { |
||
416 | $index[] = "INDEX(`$field`)"; |
||
417 | } |
||
418 | } |
||
419 | if (isset($field_def['unique_index'])) { |
||
420 | if ($field_def['unique_index']) { |
||
421 | $index[] = "UNIQUE(`$field`)"; |
||
422 | } |
||
423 | } |
||
424 | if (isset($field_def['primary'])) { |
||
425 | if ($field_def['primary']) { |
||
426 | $primary[] = "`$field`"; |
||
427 | } |
||
428 | } |
||
429 | if (isset($field_def['auto'])) { |
||
430 | if ($field_def['auto']) { |
||
431 | $field_def['extra'] = isset($field_def['extra']) ? $field_def['extra'] . " AUTO_INCREMENT" : "AUTO_INCREMENT"; |
||
432 | } |
||
433 | } |
||
434 | if (isset($field_def['extra'])) { |
||
435 | $extra = $field_def['extra']; |
||
436 | } else { |
||
437 | $extra = ""; |
||
438 | } |
||
439 | $create_lines[] = "`$field` " . $field_def['type'] . $size . ' ' . $not_null . ' ' . $extra; |
||
440 | } |
||
441 | $create_sql.= join(',', $create_lines); |
||
442 | $last_lines = array(); |
||
443 | if (count($primary)) { |
||
444 | $last_lines[] = 'PRIMARY KEY(' . join(",", $primary) . ')'; |
||
445 | } |
||
446 | if (count($index)) { |
||
447 | $last_lines[] = join(',', $index); |
||
448 | } |
||
449 | if (count($unique_index)) { |
||
450 | $last_lines[] = join(',', $unique_index); |
||
451 | } |
||
452 | if (count($last_lines)) { |
||
453 | $create_sql.= ',' . join(',', $last_lines) . ')'; |
||
454 | } |
||
455 | return $this->query($create_sql); |
||
456 | } |
||
457 | |||
458 | /** |
||
459 | * Listar las tablas en la base de datos |
||
460 | * |
||
461 | * @return array |
||
462 | */ |
||
463 | public function list_tables() |
||
464 | { |
||
465 | return $this->fetch_all("SHOW TABLES"); |
||
466 | } |
||
467 | |||
468 | /** |
||
469 | * Listar los campos de una tabla |
||
470 | * |
||
471 | * @param string $table |
||
472 | * @return array |
||
473 | */ |
||
474 | public function describe_table($table, $schema='') |
||
475 | { |
||
476 | if ($schema == '') { |
||
477 | return $this->fetch_all("DESCRIBE `$table`"); |
||
478 | } else { |
||
479 | return $this->fetch_all("DESCRIBE `$schema`.`$table`"); |
||
480 | } |
||
481 | } |
||
482 | |||
483 | /** |
||
484 | * Devuelve fila por fila el contenido de un select |
||
485 | * |
||
486 | * @param resource $result_query |
||
487 | * @param string $class clase de objeto |
||
488 | * @return object |
||
489 | */ |
||
490 | public function fetch_object($result_query=null, $class='stdClass') |
||
491 | { |
||
492 | if (!$result_query) { |
||
493 | $result_query = $this->last_result_query; |
||
494 | } |
||
495 | return mysql_fetch_object($result_query, $class); |
||
496 | } |
||
497 | |||
498 | /** |
||
499 | * Devuelve la ultima sentencia sql ejecutada por el Adaptador |
||
500 | * |
||
501 | * @return string |
||
502 | */ |
||
503 | public function last_sql_query() |
||
504 | { |
||
505 | return $this->last_query; |
||
506 | } |
||
507 | |||
508 | } |
||
509 |