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 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, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
18 | class Database { |
||
19 | use Profilable; |
||
20 | use Loggable; |
||
21 | |||
22 | const DELAYED_QUERY = 'q'; |
||
23 | const DELAYED_TYPE = 't'; |
||
24 | const DELAYED_HANDLER = 'h'; |
||
25 | const DELAYED_PARAMS = 'p'; |
||
26 | |||
27 | /** |
||
28 | * @var string $table_prefix Prefix for database tables |
||
29 | */ |
||
30 | private $table_prefix; |
||
31 | |||
32 | /** |
||
33 | * @var Connection[] |
||
34 | */ |
||
35 | private $connections = []; |
||
36 | |||
37 | /** |
||
38 | * @var int $query_count The number of queries made |
||
39 | */ |
||
40 | private $query_count = 0; |
||
41 | |||
42 | /** |
||
43 | * Query cache for select queries. |
||
44 | * |
||
45 | * Queries and their results are stored in this cache as: |
||
46 | * <code> |
||
47 | * $DB_QUERY_CACHE[query hash] => array(result1, result2, ... resultN) |
||
48 | * </code> |
||
49 | * @see \Elgg\Database::getResults() for details on the hash. |
||
50 | * |
||
51 | * @var \Elgg\Cache\LRUCache $query_cache The cache |
||
52 | */ |
||
53 | private $query_cache = null; |
||
54 | |||
55 | /** |
||
56 | * @var int $query_cache_size The number of queries to cache |
||
57 | */ |
||
58 | private $query_cache_size = 50; |
||
59 | |||
60 | /** |
||
61 | * Queries are saved as an array with the DELAYED_* constants as keys. |
||
62 | * |
||
63 | * @see registerDelayedQuery |
||
64 | * |
||
65 | * @var array $delayed_queries Queries to be run during shutdown |
||
66 | */ |
||
67 | private $delayed_queries = []; |
||
68 | |||
69 | /** |
||
70 | * @var \Elgg\Database\DbConfig $config Database configuration |
||
71 | */ |
||
72 | private $config; |
||
73 | |||
74 | /** |
||
75 | * Constructor |
||
76 | * |
||
77 | * @param DbConfig $config DB configuration |
||
78 | */ |
||
79 | 3711 | public function __construct(DbConfig $config) { |
|
82 | |||
83 | /** |
||
84 | * Reset the connections with new credentials |
||
85 | * |
||
86 | * @param DbConfig $config DB config |
||
87 | */ |
||
88 | 3711 | public function resetConnections(DbConfig $config) { |
|
94 | |||
95 | /** |
||
96 | * Gets (if required, also creates) a DB connection. |
||
97 | * |
||
98 | * @param string $type The type of link we want: "read", "write" or "readwrite". |
||
99 | * |
||
100 | * @return Connection |
||
101 | * @throws \DatabaseException |
||
102 | * @access private |
||
103 | */ |
||
104 | 293 | public function getConnection($type) { |
|
105 | 293 | if (isset($this->connections[$type])) { |
|
106 | 293 | return $this->connections[$type]; |
|
107 | 293 | } else if (isset($this->connections['readwrite'])) { |
|
108 | 293 | return $this->connections['readwrite']; |
|
109 | } else { |
||
110 | 293 | $this->setupConnections(); |
|
111 | 293 | return $this->getConnection($type); |
|
112 | } |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * Establish database connections |
||
117 | * |
||
118 | * If the configuration has been set up for multiple read/write databases, set those |
||
119 | * links up separately; otherwise just create the one database link. |
||
120 | * |
||
121 | * @return void |
||
122 | * @throws \DatabaseException |
||
123 | * @access private |
||
124 | */ |
||
125 | 293 | public function setupConnections() { |
|
126 | 293 | if ($this->config->isDatabaseSplit()) { |
|
127 | $this->connect('read'); |
||
128 | $this->connect('write'); |
||
129 | } else { |
||
130 | 293 | $this->connect('readwrite'); |
|
131 | } |
||
132 | 293 | } |
|
133 | |||
134 | /** |
||
135 | * Establish a connection to the database server |
||
136 | * |
||
137 | * Connect to the database server and use the Elgg database for a particular database link |
||
138 | * |
||
139 | * @param string $type The type of database connection. "read", "write", or "readwrite". |
||
140 | * |
||
141 | * @return void |
||
142 | * @throws \DatabaseException |
||
143 | * @access private |
||
144 | */ |
||
145 | 293 | public function connect($type = "readwrite") { |
|
146 | 293 | $conf = $this->config->getConnectionConfig($type); |
|
147 | |||
148 | $params = [ |
||
149 | 293 | 'dbname' => $conf['database'], |
|
150 | 293 | 'user' => $conf['user'], |
|
151 | 293 | 'password' => $conf['password'], |
|
152 | 293 | 'host' => $conf['host'], |
|
153 | 293 | 'charset' => $conf['encoding'], |
|
154 | 293 | 'driver' => 'pdo_mysql', |
|
155 | ]; |
||
156 | |||
157 | try { |
||
158 | 293 | $this->connections[$type] = DriverManager::getConnection($params); |
|
159 | 293 | $this->connections[$type]->setFetchMode(\PDO::FETCH_OBJ); |
|
160 | |||
161 | // https://github.com/Elgg/Elgg/issues/8121 |
||
162 | 293 | $sub_query = "SELECT REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', '')"; |
|
163 | 293 | $this->connections[$type]->exec("SET SESSION sql_mode=($sub_query);"); |
|
164 | } catch (\Exception $e) { |
||
165 | // http://dev.mysql.com/doc/refman/5.1/en/error-messages-server.html |
||
166 | if ($e->getCode() == 1102 || $e->getCode() == 1049) { |
||
167 | $msg = "Elgg couldn't select the database '{$conf['database']}'. " |
||
168 | . "Please check that the database is created and you have access to it."; |
||
169 | } else { |
||
170 | $msg = "Elgg couldn't connect to the database using the given credentials. Check the settings file."; |
||
171 | } |
||
172 | throw new \DatabaseException($msg); |
||
173 | } |
||
174 | 293 | } |
|
175 | |||
176 | /** |
||
177 | * Retrieve rows from the database. |
||
178 | * |
||
179 | * Queries are executed with {@link \Elgg\Database::executeQuery()} and results |
||
180 | * are retrieved with {@link \PDO::fetchObject()}. If a callback |
||
181 | * function $callback is defined, each row will be passed as a single |
||
182 | * argument to $callback. If no callback function is defined, the |
||
183 | * entire result set is returned as an array. |
||
184 | * |
||
185 | * @param string $query The query being passed. |
||
186 | * @param callable $callback Optionally, the name of a function to call back to on each row |
||
187 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
188 | * |
||
189 | * @return array An array of database result objects or callback function results. If the query |
||
190 | * returned nothing, an empty array. |
||
191 | * @throws \DatabaseException |
||
192 | */ |
||
193 | 3711 | public function getData($query, $callback = null, array $params = []) { |
|
196 | |||
197 | /** |
||
198 | * Retrieve a single row from the database. |
||
199 | * |
||
200 | * Similar to {@link \Elgg\Database::getData()} but returns only the first row |
||
201 | * matched. If a callback function $callback is specified, the row will be passed |
||
202 | * as the only argument to $callback. |
||
203 | * |
||
204 | * @param string $query The query to execute. |
||
205 | * @param callable $callback A callback function to apply to the row |
||
206 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
207 | * |
||
208 | * @return mixed A single database result object or the result of the callback function. |
||
209 | * @throws \DatabaseException |
||
210 | */ |
||
211 | 3711 | public function getDataRow($query, $callback = null, array $params = []) { |
|
214 | |||
215 | /** |
||
216 | * Insert a row into the database. |
||
217 | * |
||
218 | * @note Altering the DB invalidates all queries in the query cache. |
||
219 | * |
||
220 | * @param string $query The query to execute. |
||
221 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
222 | * |
||
223 | * @return int|false The database id of the inserted row if a AUTO_INCREMENT field is |
||
224 | * defined, 0 if not, and false on failure. |
||
225 | * @throws \DatabaseException |
||
226 | */ |
||
227 | 3625 | View Code Duplication | public function insertData($query, array $params = []) { |
240 | |||
241 | /** |
||
242 | * Update the database. |
||
243 | * |
||
244 | * @note Altering the DB invalidates all queries in the query cache. |
||
245 | * |
||
246 | * @note WARNING! update_data() has the 2nd and 3rd arguments reversed. |
||
247 | * |
||
248 | * @param string $query The query to run. |
||
249 | * @param bool $get_num_rows Return the number of rows affected (default: false). |
||
250 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
251 | * |
||
252 | * @return bool|int |
||
253 | * @throws \DatabaseException |
||
254 | */ |
||
255 | 90 | public function updateData($query, $get_num_rows = false, array $params = []) { |
|
270 | |||
271 | /** |
||
272 | * Delete data from the database |
||
273 | * |
||
274 | * @note Altering the DB invalidates all queries in query cache. |
||
275 | * |
||
276 | * @param string $query The SQL query to run |
||
277 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
278 | * |
||
279 | * @return int The number of affected rows |
||
280 | * @throws \DatabaseException |
||
281 | */ |
||
282 | 219 | View Code Duplication | public function deleteData($query, array $params = []) { |
295 | |||
296 | /** |
||
297 | * Get a string that uniquely identifies a callback during the current request. |
||
298 | * |
||
299 | * This is used to cache queries whose results were transformed by the callback. If the callback involves |
||
300 | * object method calls of the same class, different instances will return different values. |
||
301 | * |
||
302 | * @param callable $callback The callable value to fingerprint |
||
303 | * |
||
304 | * @return string A string that is unique for each callable passed in |
||
305 | * @since 1.9.4 |
||
306 | * @access private |
||
307 | */ |
||
308 | 3616 | View Code Duplication | protected function fingerprintCallback($callback) { |
324 | |||
325 | /** |
||
326 | * Handles queries that return results, running the results through a |
||
327 | * an optional callback function. This is for R queries (from CRUD). |
||
328 | * |
||
329 | * @param string $query The select query to execute |
||
330 | * @param string $callback An optional callback function to run on each row |
||
331 | * @param bool $single Return only a single result? |
||
332 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
333 | * |
||
334 | * @return array An array of database result objects or callback function results. If the query |
||
335 | * returned nothing, an empty array. |
||
336 | * @throws \DatabaseException |
||
337 | */ |
||
338 | 3711 | protected function getResults($query, $callback = null, $single = false, array $params = []) { |
|
394 | |||
395 | /** |
||
396 | * Execute a query. |
||
397 | * |
||
398 | * $query is executed via {@link Connection::query}. If there is an SQL error, |
||
399 | * a {@link DatabaseException} is thrown. |
||
400 | * |
||
401 | * @param string $query The query |
||
402 | * @param Connection $connection The DB connection |
||
403 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
404 | * |
||
405 | * @return Statement The result of the query |
||
406 | * @throws \DatabaseException |
||
407 | */ |
||
408 | 3711 | protected function executeQuery($query, Connection $connection, array $params = []) { |
|
439 | |||
440 | /** |
||
441 | * Runs a full database script from disk. |
||
442 | * |
||
443 | * The file specified should be a standard SQL file as created by |
||
444 | * mysqldump or similar. Statements must be terminated with ; |
||
445 | * and a newline character (\n or \r\n). |
||
446 | * |
||
447 | * The special string 'prefix_' is replaced with the database prefix |
||
448 | * as defined in {@link $this->tablePrefix}. |
||
449 | * |
||
450 | * @warning Only single line comments are supported. A comment |
||
451 | * must start with '-- ' or '# ', where the comment sign is at the |
||
452 | * very beginning of each line. |
||
453 | * |
||
454 | * @warning Errors do not halt execution of the script. If a line |
||
455 | * generates an error, the error message is saved and the |
||
456 | * next line is executed. After the file is run, any errors |
||
457 | * are displayed as a {@link DatabaseException} |
||
458 | * |
||
459 | * @param string $scriptlocation The full path to the script |
||
460 | * |
||
461 | * @return void |
||
462 | * @throws \DatabaseException |
||
463 | * @access private |
||
464 | */ |
||
465 | 5 | public function runSqlScript($scriptlocation) { |
|
501 | |||
502 | /** |
||
503 | * Queue a query for execution upon shutdown. |
||
504 | * |
||
505 | * You can specify a callback if you care about the result. This function will always |
||
506 | * be passed a \Doctrine\DBAL\Driver\Statement. |
||
507 | * |
||
508 | * @param string $query The query to execute |
||
509 | * @param string $type The query type ('read' or 'write') |
||
510 | * @param callable $callback A callback function to pass the results array to |
||
511 | * @param array $params Query params. E.g. [1, 'steve'] or [':id' => 1, ':name' => 'steve'] |
||
512 | * |
||
513 | * @return boolean Whether registering was successful. |
||
514 | * @access private |
||
515 | */ |
||
516 | 166 | public function registerDelayedQuery($query, $type, $callback = null, array $params = []) { |
|
530 | |||
531 | /** |
||
532 | * Trigger all queries that were registered as "delayed" queries. This is |
||
533 | * called by the system automatically on shutdown. |
||
534 | * |
||
535 | * @return void |
||
536 | * @access private |
||
537 | * @todo make protected once this class is part of public API |
||
538 | */ |
||
539 | 1 | public function executeDelayedQueries() { |
|
561 | |||
562 | /** |
||
563 | * Enable the query cache |
||
564 | * |
||
565 | * This does not take precedence over the \Elgg\Database\Config setting. |
||
566 | * |
||
567 | * @return void |
||
568 | * @access private |
||
569 | */ |
||
570 | 3711 | public function enableQueryCache() { |
|
576 | |||
577 | /** |
||
578 | * Disable the query cache |
||
579 | * |
||
580 | * This is useful for special scripts that pull large amounts of data back |
||
581 | * in single queries. |
||
582 | * |
||
583 | * @return void |
||
584 | * @access private |
||
585 | */ |
||
586 | 3615 | public function disableQueryCache() { |
|
589 | |||
590 | /** |
||
591 | * Invalidate the query cache |
||
592 | * |
||
593 | * @return void |
||
594 | */ |
||
595 | 3627 | protected function invalidateQueryCache() { |
|
603 | |||
604 | /** |
||
605 | * Get the number of queries made to the database |
||
606 | * |
||
607 | * @return int |
||
608 | * @access private |
||
609 | */ |
||
610 | 1 | public function getQueryCount() { |
|
613 | |||
614 | /** |
||
615 | * Sanitizes an integer value for use in a query |
||
616 | * |
||
617 | * @param int $value Value to sanitize |
||
618 | * @param bool $signed Whether negative values are allowed (default: true) |
||
619 | * @return int |
||
620 | * @deprecated Use query parameters where possible |
||
621 | */ |
||
622 | 3711 | public function sanitizeInt($value, $signed = true) { |
|
633 | |||
634 | /** |
||
635 | * Sanitizes a string for use in a query |
||
636 | * |
||
637 | * @param string $value Value to escape |
||
638 | * @return string |
||
639 | * @throws \DatabaseException |
||
640 | * @deprecated Use query parameters where possible |
||
641 | */ |
||
642 | 293 | public function sanitizeString($value) { |
|
652 | |||
653 | /** |
||
654 | * Get the server version number |
||
655 | * |
||
656 | * @param string $type Connection type (Config constants, e.g. Config::READ_WRITE) |
||
657 | * |
||
658 | * @return string Empty if version cannot be determined |
||
659 | * @access private |
||
660 | */ |
||
661 | public function getServerVersion($type) { |
||
669 | |||
670 | /** |
||
671 | * Handle magic property reads |
||
672 | * |
||
673 | * @param string $name Property name |
||
674 | * @return mixed |
||
675 | */ |
||
676 | 3711 | public function __get($name) { |
|
683 | |||
684 | /** |
||
685 | * Handle magic property writes |
||
686 | * |
||
687 | * @param string $name Property name |
||
688 | * @param mixed $value Value |
||
689 | * @return void |
||
690 | */ |
||
691 | public function __set($name, $value) { |
||
694 | } |
||
695 |
This check looks at variables that have been passed in as parameters and are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.