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 Connection 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 Connection, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
46 | class Connection extends \Doctrine\DBAL\Connection implements IDBConnection { |
||
47 | /** |
||
48 | * @var string $tablePrefix |
||
49 | */ |
||
50 | protected $tablePrefix; |
||
51 | |||
52 | /** |
||
53 | * @var \OC\DB\Adapter $adapter |
||
54 | */ |
||
55 | protected $adapter; |
||
56 | |||
57 | protected $lockedTable = null; |
||
58 | |||
59 | public function connect() { |
||
60 | try { |
||
61 | return parent::connect(); |
||
62 | } catch (DBALException $e) { |
||
63 | // throw a new exception to prevent leaking info from the stacktrace |
||
64 | throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
||
65 | } |
||
66 | } |
||
67 | |||
68 | /** |
||
69 | * Returns a QueryBuilder for the connection. |
||
70 | * |
||
71 | * @return \OCP\DB\QueryBuilder\IQueryBuilder |
||
72 | */ |
||
73 | public function getQueryBuilder() { |
||
74 | return new QueryBuilder($this); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Gets the QueryBuilder for the connection. |
||
79 | * |
||
80 | * @return \Doctrine\DBAL\Query\QueryBuilder |
||
81 | * @deprecated please use $this->getQueryBuilder() instead |
||
82 | */ |
||
83 | public function createQueryBuilder() { |
||
84 | $backtrace = $this->getCallerBacktrace(); |
||
85 | \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
||
86 | return parent::createQueryBuilder(); |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * Gets the ExpressionBuilder for the connection. |
||
91 | * |
||
92 | * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
||
93 | * @deprecated please use $this->getQueryBuilder()->expr() instead |
||
94 | */ |
||
95 | public function getExpressionBuilder() { |
||
96 | $backtrace = $this->getCallerBacktrace(); |
||
97 | \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
||
98 | return parent::getExpressionBuilder(); |
||
99 | } |
||
100 | |||
101 | /** |
||
102 | * Get the file and line that called the method where `getCallerBacktrace()` was used |
||
103 | * |
||
104 | * @return string |
||
105 | */ |
||
106 | protected function getCallerBacktrace() { |
||
107 | $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
||
108 | |||
109 | // 0 is the method where we use `getCallerBacktrace` |
||
110 | // 1 is the target method which uses the method we want to log |
||
111 | if (isset($traces[1])) { |
||
112 | return $traces[1]['file'] . ':' . $traces[1]['line']; |
||
113 | } |
||
114 | |||
115 | return ''; |
||
116 | } |
||
117 | |||
118 | /** |
||
119 | * @return string |
||
120 | */ |
||
121 | public function getPrefix() { |
||
122 | return $this->tablePrefix; |
||
123 | } |
||
124 | |||
125 | /** |
||
126 | * Initializes a new instance of the Connection class. |
||
127 | * |
||
128 | * @param array $params The connection parameters. |
||
129 | * @param \Doctrine\DBAL\Driver $driver |
||
130 | * @param \Doctrine\DBAL\Configuration $config |
||
131 | * @param \Doctrine\Common\EventManager $eventManager |
||
132 | * @throws \Exception |
||
133 | */ |
||
134 | public function __construct(array $params, Driver $driver, Configuration $config = null, |
||
135 | EventManager $eventManager = null) |
||
136 | { |
||
137 | if (!isset($params['adapter'])) { |
||
138 | throw new \Exception('adapter not set'); |
||
139 | } |
||
140 | if (!isset($params['tablePrefix'])) { |
||
141 | throw new \Exception('tablePrefix not set'); |
||
142 | } |
||
143 | parent::__construct($params, $driver, $config, $eventManager); |
||
144 | $this->adapter = new $params['adapter']($this); |
||
145 | $this->tablePrefix = $params['tablePrefix']; |
||
146 | |||
147 | parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
||
|
|||
148 | } |
||
149 | |||
150 | /** |
||
151 | * Prepares an SQL statement. |
||
152 | * |
||
153 | * @param string $statement The SQL statement to prepare. |
||
154 | * @param int $limit |
||
155 | * @param int $offset |
||
156 | * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
||
157 | */ |
||
158 | public function prepare( $statement, $limit=null, $offset=null ) { |
||
159 | if ($limit === -1) { |
||
160 | $limit = null; |
||
161 | } |
||
162 | if (!is_null($limit)) { |
||
163 | $platform = $this->getDatabasePlatform(); |
||
164 | $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
||
165 | } |
||
166 | $statement = $this->replaceTablePrefix($statement); |
||
167 | $statement = $this->adapter->fixupStatement($statement); |
||
168 | |||
169 | return parent::prepare($statement); |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * Executes an, optionally parametrized, SQL query. |
||
174 | * |
||
175 | * If the query is parametrized, a prepared statement is used. |
||
176 | * If an SQLLogger is configured, the execution is logged. |
||
177 | * |
||
178 | * @param string $query The SQL query to execute. |
||
179 | * @param array $params The parameters to bind to the query, if any. |
||
180 | * @param array $types The types the previous parameters are in. |
||
181 | * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
||
182 | * |
||
183 | * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
||
184 | * |
||
185 | * @throws \Doctrine\DBAL\DBALException |
||
186 | */ |
||
187 | public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) |
||
193 | |||
194 | /** |
||
195 | * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
||
196 | * and returns the number of affected rows. |
||
197 | * |
||
198 | * This method supports PDO binding types as well as DBAL mapping types. |
||
199 | * |
||
200 | * @param string $query The SQL query. |
||
201 | * @param array $params The query parameters. |
||
202 | * @param array $types The parameter types. |
||
203 | * |
||
204 | * @return integer The number of affected rows. |
||
205 | * |
||
206 | * @throws \Doctrine\DBAL\DBALException |
||
207 | */ |
||
208 | public function executeUpdate($query, array $params = [], array $types = []) |
||
214 | |||
215 | /** |
||
216 | * Returns the ID of the last inserted row, or the last value from a sequence object, |
||
217 | * depending on the underlying driver. |
||
218 | * |
||
219 | * Note: This method may not return a meaningful or consistent result across different drivers, |
||
220 | * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
||
221 | * columns or sequences. |
||
222 | * |
||
223 | * @param string $seqName Name of the sequence object from which the ID should be returned. |
||
224 | * @return string A string representation of the last inserted ID. |
||
225 | */ |
||
226 | public function lastInsertId($seqName = null) { |
||
232 | |||
233 | // internal use |
||
234 | public function realLastInsertId($seqName = null) { |
||
237 | |||
238 | /** |
||
239 | * Insert a row if the matching row does not exists. |
||
240 | * |
||
241 | * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
||
242 | * @param array $input data that should be inserted into the table (column name => value) |
||
243 | * @param array|null $compare List of values that should be checked for "if not exists" |
||
244 | * If this is null or an empty array, all keys of $input will be compared |
||
245 | * Please note: text fields (clob) must not be used in the compare array |
||
246 | * @return int number of inserted rows |
||
247 | * @throws \Doctrine\DBAL\DBALException |
||
248 | */ |
||
249 | public function insertIfNotExist($table, $input, array $compare = null) { |
||
252 | |||
253 | /** |
||
254 | * Attempt to update a row, else insert a new one |
||
255 | * |
||
256 | * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
||
257 | * @param array $input data that should be inserted into the table (column name => value) |
||
258 | * @param array|null $compare List of values that should be checked for "if not exists" |
||
259 | * If this is null or an empty array, all keys of $input will be compared |
||
260 | * Please note: text fields (clob) must not be used in the compare array |
||
261 | * @return int number of affected rows |
||
262 | * @throws \Doctrine\DBAL\DBALException |
||
263 | */ |
||
264 | public function upsert($table, $input, array $compare = null) { |
||
267 | |||
268 | private function getType($value) { |
||
277 | |||
278 | /** |
||
279 | * Insert or update a row value. |
||
280 | * |
||
281 | * @param string $table |
||
282 | * @param array $keys (column name => value) |
||
283 | * @param array $values (column name => value) |
||
284 | * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
||
285 | * @return int number of new rows |
||
286 | * @throws \Doctrine\DBAL\DBALException |
||
287 | * @throws PreConditionNotMetException |
||
288 | */ |
||
289 | public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
||
323 | |||
324 | /** |
||
325 | * Create an exclusive read+write lock on a table |
||
326 | * |
||
327 | * @param string $tableName |
||
328 | * @throws \BadMethodCallException When trying to acquire a second lock |
||
329 | * @since 9.1.0 |
||
330 | */ |
||
331 | public function lockTable($tableName) { |
||
340 | |||
341 | /** |
||
342 | * Release a previous acquired lock again |
||
343 | * |
||
344 | * @since 9.1.0 |
||
345 | */ |
||
346 | public function unlockTable() { |
||
350 | |||
351 | /** |
||
352 | * returns the error code and message as a string for logging |
||
353 | * works with DoctrineException |
||
354 | * @return string |
||
355 | */ |
||
356 | public function getError() { |
||
366 | |||
367 | /** |
||
368 | * Drop a table from the database if it exists |
||
369 | * |
||
370 | * @param string $table table name without the prefix |
||
371 | */ |
||
372 | View Code Duplication | public function dropTable($table) { |
|
379 | |||
380 | /** |
||
381 | * Check if a table exists |
||
382 | * |
||
383 | * @param string $table table name without the prefix |
||
384 | * @return bool |
||
385 | */ |
||
386 | public function tableExists($table){ |
||
391 | |||
392 | // internal use |
||
393 | /** |
||
394 | * @param string $statement |
||
395 | * @return string |
||
396 | */ |
||
397 | protected function replaceTablePrefix($statement) { |
||
400 | |||
401 | /** |
||
402 | * Check if a transaction is active |
||
403 | * |
||
404 | * @return bool |
||
405 | * @since 8.2.0 |
||
406 | */ |
||
407 | public function inTransaction() { |
||
410 | |||
411 | /** |
||
412 | * Espace a parameter to be used in a LIKE query |
||
413 | * |
||
414 | * @param string $param |
||
415 | * @return string |
||
416 | */ |
||
417 | public function escapeLikeParameter($param) { |
||
420 | |||
421 | /** |
||
422 | * Create the schema of the connected database |
||
423 | * |
||
424 | * @return Schema |
||
425 | */ |
||
426 | public function createSchema() { |
||
431 | |||
432 | /** |
||
433 | * Migrate the database to the given schema |
||
434 | * |
||
435 | * @param Schema $toSchema |
||
436 | */ |
||
437 | public function migrateToSchema(Schema $toSchema) { |
||
442 | |||
443 | /** |
||
444 | * Are 4-byte characters allowed or only 3-byte |
||
445 | * |
||
446 | * @return bool |
||
447 | * @since 10.0 |
||
448 | */ |
||
449 | public function allows4ByteCharacters() { |
||
458 | |||
459 | /** |
||
460 | * Returns the version of the related platform if applicable. |
||
461 | * |
||
462 | * Returns null if either the driver is not capable to create version |
||
463 | * specific platform instances, no explicit server version was specified |
||
464 | * or the underlying driver connection cannot determine the platform |
||
465 | * version without having to query it (performance reasons). |
||
466 | * |
||
467 | * @return null|string |
||
468 | */ |
||
469 | public function getDatabaseVersionString() |
||
481 | } |
||
482 |
This check looks for a call to a parent method whose name is different than the method from which it is called.
Consider the following code:
The
getFirstName()
method in theSon
calls the wrong method in the parent class.