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:
| 1 | <?php |
||
| 18 | class TermFieldLengthNorm |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * @var \PDO |
||
| 22 | */ |
||
| 23 | protected $dbHandle; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * TermFieldLengthNorm constructor. |
||
| 27 | * |
||
| 28 | * @param \PDO $dbHandle |
||
| 29 | */ |
||
| 30 | public function __construct($dbHandle) |
||
| 31 | { |
||
| 32 | $this->dbHandle = $dbHandle; |
||
| 33 | } |
||
| 34 | |||
| 35 | public function execute() |
||
| 36 | { |
||
| 37 | $db = $this->dbHandle; |
||
| 38 | $db->sqliteCreateFunction('sqrt', 'sqrt', 1); |
||
| 39 | $sql = ' |
||
| 40 | SELECT documentPath, field, COUNT(`count`) as termCount |
||
| 41 | FROM term_count |
||
| 42 | GROUP BY documentPath, field |
||
| 43 | '; |
||
| 44 | $stmt = $db->prepare($sql); |
||
| 45 | View Code Duplication | if ($stmt === false) { |
|
|
|
|||
| 46 | $errorInfo = $db->errorInfo(); |
||
| 47 | $errorMsg = $errorInfo[2]; |
||
| 48 | throw new \Exception('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); |
||
| 49 | } |
||
| 50 | View Code Duplication | if (($stmt->execute()) === false) { |
|
| 51 | $errorInfo = $db->errorInfo(); |
||
| 52 | $errorMsg = $errorInfo[2]; |
||
| 53 | throw new \Exception('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); |
||
| 54 | } |
||
| 55 | $uniqueFieldsPerDocument = $stmt->fetchAll(\PDO::FETCH_OBJ); |
||
| 56 | $values = array(); |
||
| 57 | $i = 0; |
||
| 58 | foreach ($uniqueFieldsPerDocument as $fieldRow) { |
||
| 59 | $values[] = 'UPDATE term_frequency SET termNorm = 1/sqrt(' . intval($fieldRow->termCount) . ') WHERE documentPath = ' . $db->quote($fieldRow->documentPath) . ' AND field = ' . $db->quote($fieldRow->field) . ';'; |
||
| 60 | $i += 1; |
||
| 61 | if ($i >= Indexer::SQLITE_MAX_COMPOUND_SELECT) { |
||
| 62 | $this->executeUpdateTermNorm($values, $db); |
||
| 63 | $values = array(); |
||
| 64 | $i = 0; |
||
| 65 | } |
||
| 66 | } |
||
| 67 | if (count($values) != 0) { |
||
| 68 | $this->executeUpdateTermNorm($values, $db); |
||
| 69 | } |
||
| 70 | } |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @param array $values |
||
| 74 | * @param \PDO $db |
||
| 75 | * @throws \Exception |
||
| 76 | */ |
||
| 77 | private function executeUpdateTermNorm($values, $db) |
||
| 88 | } |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.