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 DbMsSQL 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 DbMsSQL, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
29 | class DbMsSQL extends DbBase implements DbBaseInterface { |
||
30 | |||
31 | /** |
||
32 | * Resource de la Conexión a MsSQL |
||
33 | * |
||
34 | * @var resource |
||
35 | */ |
||
36 | public $id_connection; |
||
37 | |||
38 | /** |
||
39 | * Último Resultado de una Query |
||
40 | * |
||
41 | * @var resource |
||
42 | */ |
||
43 | public $last_result_query; |
||
44 | |||
45 | /** |
||
46 | * Última sentencia SQL enviada a MsSQL |
||
47 | * |
||
48 | * @var string |
||
49 | */ |
||
50 | protected $last_query; |
||
51 | |||
52 | /** |
||
53 | * Último error generado por MsSQL |
||
54 | * |
||
55 | * @var string |
||
56 | */ |
||
57 | public $last_error; |
||
58 | |||
59 | /** |
||
60 | * Resultado de Array Asociativo |
||
61 | * |
||
62 | */ |
||
63 | const DB_ASSOC = MSSQL_ASSOC; |
||
64 | |||
65 | /** |
||
66 | * Resultado de Array Asociativo y Numérico |
||
67 | * |
||
68 | */ |
||
69 | const DB_BOTH = MSSQL_BOTH; |
||
70 | |||
71 | /** |
||
72 | * Resultado de Array Numérico |
||
73 | * |
||
74 | */ |
||
75 | const DB_NUM = MSSQL_NUM; |
||
76 | |||
77 | /** |
||
78 | * Tipo de Dato Integer |
||
79 | * |
||
80 | */ |
||
81 | const TYPE_INTEGER = 'INT'; |
||
82 | |||
83 | /** |
||
84 | * Tipo de Dato Date |
||
85 | * |
||
86 | */ |
||
87 | const TYPE_DATE = 'SMALLDATETIME'; |
||
88 | |||
89 | /** |
||
90 | * Tipo de Dato Varchar |
||
91 | * |
||
92 | */ |
||
93 | const TYPE_VARCHAR = 'VARCHAR'; |
||
94 | |||
95 | /** |
||
96 | * Tipo de Dato Decimal |
||
97 | * |
||
98 | */ |
||
99 | const TYPE_DECIMAL = 'DECIMAL'; |
||
100 | |||
101 | /** |
||
102 | * Tipo de Dato Datetime |
||
103 | * |
||
104 | */ |
||
105 | const TYPE_DATETIME = 'DATETIME'; |
||
106 | |||
107 | /** |
||
108 | * Tipo de Dato Char |
||
109 | * |
||
110 | */ |
||
111 | const TYPE_CHAR = 'CHAR'; |
||
112 | |||
113 | /** |
||
114 | * Hace una conexión a la base de datos de MsSQL |
||
115 | * |
||
116 | * @param array $config |
||
117 | * @return bool |
||
118 | */ |
||
119 | public function connect($config){ |
||
120 | if(!extension_loaded('mssql')){ |
||
121 | throw new KumbiaException('Debe cargar la extensión de PHP llamada php_mssql'); |
||
122 | } |
||
123 | if(!isset($config['port']) || !$config['port']) { |
||
124 | $config['port'] = 1433; |
||
125 | } |
||
126 | //if($this->id_connection = mssql_connect("{$config['host']},{$config['port']}", $config['username'], $config['password'], true)){ |
||
127 | if($this->id_connection = mssql_connect($config['host'], $config['username'], $config['password'], true)){ |
||
128 | if($config['name']!=='') { |
||
129 | if(!mssql_select_db($config['name'], $this->id_connection)){ |
||
130 | throw new KumbiaException($this->error()); |
||
131 | } |
||
132 | } |
||
133 | return true; |
||
134 | } else { |
||
135 | throw new KumbiaException($this->error()); |
||
136 | } |
||
137 | } |
||
138 | /** |
||
139 | * Efectua operaciones SQL sobre la base de datos |
||
140 | * |
||
141 | * @param string $sql_query |
||
142 | * @return resource or false |
||
143 | */ |
||
144 | public function query($sql_query){ |
||
145 | $this->debug($sql_query); |
||
146 | if($this->logger){ |
||
147 | Logger::debug($sql_query); |
||
148 | } |
||
149 | |||
150 | $this->last_query = $sql_query; |
||
151 | if($result_query = mssql_query($sql_query, $this->id_connection)){ |
||
152 | $this->last_result_query = $result_query; |
||
153 | return $result_query; |
||
154 | }else{ |
||
155 | throw new KumbiaException($this->error(" al ejecutar <em>\"$sql_query\"</em>")); |
||
156 | } |
||
157 | } |
||
158 | /** |
||
159 | * Cierra la Conexión al Motor de Base de datos |
||
160 | */ |
||
161 | public function close(){ |
||
162 | if($this->id_connection) { |
||
163 | return mssql_close(); |
||
164 | } |
||
165 | return false; |
||
166 | } |
||
167 | /** |
||
168 | * Devuelve fila por fila el contenido de un select |
||
169 | * |
||
170 | * @param resource $result_query |
||
171 | * @param int $opt |
||
172 | * @return array |
||
173 | */ |
||
174 | public function fetch_array($result_query='', $opt=MSSQL_BOTH){ |
||
175 | |||
176 | if(!$result_query){ |
||
177 | $result_query = $this->last_result_query; |
||
178 | if(!$result_query){ |
||
179 | return false; |
||
180 | } |
||
181 | } |
||
182 | return mssql_fetch_array($result_query, $opt); |
||
183 | } |
||
184 | /** |
||
185 | * Constructor de la Clase |
||
186 | * |
||
187 | * @param array $config |
||
188 | */ |
||
189 | public function __construct($config){ |
||
190 | $this->connect($config); |
||
191 | } |
||
192 | /** |
||
193 | * Devuelve el número de filas de un select |
||
194 | */ |
||
195 | public function num_rows($result_query=''){ |
||
196 | |||
197 | if(!$result_query){ |
||
198 | $result_query = $this->last_result_query; |
||
199 | if(!$result_query){ |
||
200 | return false; |
||
201 | } |
||
202 | } |
||
203 | if(($number_rows = mssql_num_rows($result_query))!==false){ |
||
204 | return $number_rows; |
||
205 | } else { |
||
206 | throw new KumbiaException($this->error()); |
||
207 | } |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * Devuelve el nombre de un campo en el resultado de un select |
||
212 | * |
||
213 | * @param int $number |
||
214 | * @param resource $result_query |
||
215 | * @return string |
||
216 | */ |
||
217 | public function field_name($number, $result_query=''){ |
||
218 | |||
219 | if(!$result_query){ |
||
220 | $result_query = $this->last_result_query; |
||
221 | if(!$result_query){ |
||
222 | return false; |
||
223 | } |
||
224 | } |
||
225 | if(($fieldName = mssql_field_name($result_query, $number))!==false){ |
||
226 | return $fieldName; |
||
227 | } else { |
||
228 | throw new KumbiaException($this->error()); |
||
229 | } |
||
230 | } |
||
231 | /** |
||
232 | * Se Mueve al resultado indicado por $number en un select |
||
233 | * |
||
234 | * @param int $number |
||
235 | * @param resource $result_query |
||
236 | * @return boolean |
||
237 | */ |
||
238 | public function data_seek($number, $result_query=''){ |
||
239 | if(!$result_query){ |
||
240 | $result_query = $this->last_result_query; |
||
241 | if(!$result_query){ |
||
242 | return false; |
||
243 | } |
||
244 | } |
||
245 | if(($success = mssql_data_seek($result_query, $number))!==false){ |
||
246 | return $success; |
||
247 | } else { |
||
248 | throw new KumbiaException($this->error()); |
||
249 | } |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * Número de Filas afectadas en un insert, update o delete |
||
254 | * |
||
255 | * @param resource $result_query |
||
256 | * @return int |
||
257 | */ |
||
258 | public function affected_rows($result_query=''){ |
||
259 | if(($numberRows = mssql_affected_rows())!==false){ |
||
260 | return $numberRows; |
||
261 | } else { |
||
262 | throw new KumbiaException($this->error()); |
||
263 | } |
||
264 | } |
||
265 | |||
266 | /** |
||
267 | * Devuelve el error de MsSQL |
||
268 | * |
||
269 | * @return string |
||
270 | */ |
||
271 | public function error($err=''){ |
||
272 | if(!$this->id_connection){ |
||
273 | $this->last_error = mssql_get_last_message() ? mssql_get_last_message() : "[Error Desconocido en MsSQL: $err]"; |
||
274 | if($this->logger){ |
||
275 | Logger::error($this->last_error); |
||
276 | } |
||
277 | return $this->last_error; |
||
278 | } |
||
279 | $this->last_error = mssql_get_last_message() ? mssql_get_last_message() : "[Error Desconocido en MsSQL: $err]"; |
||
280 | $this->last_error.= $err; |
||
281 | if($this->logger){ |
||
282 | Logger::error($this->last_error); |
||
283 | } |
||
284 | return $this->last_error; |
||
285 | } |
||
286 | /** |
||
287 | * Devuelve el no error de MsSQL |
||
288 | * |
||
289 | * @return int |
||
290 | */ |
||
291 | public function no_error(){ |
||
292 | return mssql_errno(); |
||
293 | } |
||
294 | /** |
||
295 | * Devuelve el último id autonumérico generado en la BD |
||
296 | * |
||
297 | * @return int |
||
298 | */ |
||
299 | public function last_insert_id($table='', $primary_key=''){ |
||
300 | |||
301 | //$id = false; |
||
302 | $result = mssql_query("select max({$primary_key}) from $table"); |
||
303 | if ($row = mssql_fetch_row($result)) { |
||
304 | $this->id_connection = trim($row[0]); |
||
305 | } |
||
306 | mssql_free_result($result); |
||
307 | return $this->id_connection; |
||
308 | } |
||
309 | /** |
||
310 | * Verifica si una tabla existe o no |
||
311 | * |
||
312 | * @param string $table |
||
313 | * @return boolean |
||
314 | */ |
||
315 | public function table_exists($table, $schema=''){ |
||
316 | $table = addslashes("$table"); |
||
317 | if($schema==''){ |
||
318 | $num = $this->fetch_one("SELECT COUNT(*) FROM |
||
319 | INFORMATION_SCHEMA.TABLES |
||
320 | WHERE TABLE_NAME = '$table'"); |
||
321 | } else { |
||
322 | $schema = addslashes("$schema"); |
||
323 | $num = $this->fetch_one("SELECT COUNT(*) FROM |
||
324 | INFORMATION_SCHEMA.TABLES |
||
325 | WHERE TABLE_NAME = '$table' |
||
326 | AND TABLE_SCHEMA = '$schema'"); |
||
327 | } |
||
328 | return $num[0]; |
||
329 | } |
||
330 | /** |
||
331 | * Devuelve un LIMIT válido para un SELECT del RBDM |
||
332 | * |
||
333 | * @param string $sql consulta sql |
||
334 | * @return string |
||
335 | */ |
||
336 | public function limit($sql){ |
||
337 | $params = Util::getParams(func_get_args()); |
||
338 | |||
339 | //TODO: añadirle el offset |
||
340 | if(isset($params['limit'])){ |
||
341 | $sql = str_ireplace("SELECT ", "SELECT TOP $params[limit] ", $sql); |
||
342 | } |
||
343 | return $sql; |
||
344 | } |
||
345 | |||
346 | /** |
||
347 | * Borra una tabla de la base de datos |
||
348 | * |
||
349 | * @param string $table |
||
350 | * @return resource |
||
351 | */ |
||
352 | public function drop_table($table, $if_exists=true){ |
||
353 | if($if_exists){ |
||
354 | $sql = "IF EXISTS(SELECT TABLE_NAME FROM |
||
355 | INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table') |
||
356 | DROP TABLE $table;"; |
||
357 | return $this->query($sql); |
||
358 | } else { |
||
359 | return $this->query("DROP TABLE $table"); |
||
360 | } |
||
361 | } |
||
362 | /** |
||
363 | * Listar las tablas en la base de datos |
||
364 | * |
||
365 | * @return array |
||
366 | */ |
||
367 | public function list_tables(){ |
||
368 | return $this->fetch_all("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES"); |
||
369 | } |
||
370 | |||
371 | /** |
||
372 | * Listar los campos de una tabla |
||
373 | * |
||
374 | * @param string $table |
||
375 | * @return array |
||
376 | */ |
||
377 | /* |
||
378 | public function describe_table($table, $schema=''){ |
||
379 | $sql = "SELECT A.name as Field, |
||
380 | (case when A.isnullable=0 then 'NO' when A.isnullable=1 then 'YES' end) as 'Null', |
||
381 | (case when A.colorder=1 then 'PRI' when A.colorder>1 then '' end ) as 'Key', |
||
382 | convert(varchar, C.name) + '(' + convert(varchar, (A.length)) + ')' as 'Type', |
||
383 | (case when A.cdefault=0 then 'NULL' when A.cdefault<>0 then '0' end) as 'Default' |
||
384 | FROM syscolumns A |
||
385 | left join sysobjects B on A.id = B.id |
||
386 | left join systypes C on C.xtype = A.xtype |
||
387 | WHERE B.name = '$table'"; |
||
388 | return $this->fetch_all($sql); |
||
389 | } |
||
390 | */ |
||
391 | public function describe_table($table, $schema=''){ |
||
392 | $describeTable = $this->fetch_all("exec sp_columns @table_name = '$table'"); |
||
393 | $finalDescribe = array(); |
||
394 | foreach($describeTable as $field){ |
||
395 | $finalDescribe[] = array( |
||
396 | 'Field' => $field['COLUMN_NAME'], |
||
397 | 'Type' => $field['LENGTH'] ? $field['TYPE_NAME'] : $field['TYPE_NAME'].'('.$field['LENGTH'].')', |
||
398 | 'Null' => $field['NULLABLE'] == 1 ? 'YES' : 'NO' |
||
399 | ); |
||
400 | } |
||
401 | $describeKeys = $this->fetch_all("exec sp_pkeys @table_name = '$table'"); |
||
402 | foreach($describeKeys as $field){ |
||
403 | for($i=0;$i<=count($finalDescribe)-1;++$i){ |
||
404 | if($finalDescribe[$i]['Field']==$field['COLUMN_NAME']){ |
||
405 | $finalDescribe[$i]['Key'] = 'PRI'; |
||
406 | } else { |
||
407 | $finalDescribe[$i]['Key'] = ""; |
||
408 | } |
||
409 | } |
||
410 | } |
||
411 | return $finalDescribe; |
||
412 | } |
||
413 | |||
414 | |||
415 | /** |
||
416 | * Devuelve fila por fila el contenido de un select |
||
417 | * |
||
418 | * @param resource $result_query |
||
419 | * @return object |
||
420 | */ |
||
421 | public function fetch_object($result_query = NULL){ |
||
422 | if(!$result_query){ |
||
423 | $result_query = $this->last_result_query; |
||
424 | } |
||
425 | return mssql_fetch_object($result_query); |
||
426 | } |
||
427 | |||
428 | public function create_table ($table, $definition, $index = array()){ |
||
429 | |||
430 | } |
||
431 | } |
||
432 |