| Conditions | 4 |
| Paths | 4 |
| Total Lines | 58 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 82 | protected function dedupe($class, $mappingTable, $relationField) |
||
| 83 | { |
||
| 84 | $this->printedDots = 0; |
||
| 85 | |||
| 86 | // Find all duplicates |
||
| 87 | $itemTable = DataObject::getSchema()->tableName($class); |
||
| 88 | $duplicates = SQLSelect::create() |
||
| 89 | ->setSelect([ |
||
| 90 | 'Title' => '"Title"', |
||
| 91 | 'Count' => 'COUNT(*)', |
||
| 92 | 'UseID' => 'MIN("ID")', |
||
| 93 | ]) |
||
| 94 | ->setFrom($itemTable) |
||
| 95 | ->setGroupBy('"Title"') |
||
| 96 | ->setHaving('"Count" > 1'); |
||
| 97 | |||
| 98 | $count = $duplicates->count(); |
||
| 99 | |||
| 100 | $this->message("Found {$count} items with duplicates for type {$class}"); |
||
| 101 | |||
| 102 | if (!$count) { |
||
| 103 | return; |
||
| 104 | } |
||
| 105 | |||
| 106 | $done = 0; |
||
| 107 | foreach ($duplicates->execute() as $duplicate) { |
||
| 108 | $title = $duplicate['Title']; |
||
| 109 | $id = $duplicate['UseID']; |
||
| 110 | |||
| 111 | DB::prepared_query( |
||
| 112 | <<<SQL |
||
| 113 | UPDATE "{$mappingTable}" |
||
| 114 | INNER JOIN "{$itemTable}" ON "{$mappingTable}"."{$relationField}" = "{$itemTable}"."ID" |
||
| 115 | SET "{$mappingTable}"."{$relationField}" = ? |
||
| 116 | WHERE "{$itemTable}"."Title" = ? |
||
| 117 | SQL |
||
| 118 | , |
||
| 119 | [$id, $title] |
||
| 120 | ); |
||
| 121 | |||
| 122 | // Delete duplicates |
||
| 123 | $duplicateItems = DataObject::get($class)->filter([ |
||
| 124 | 'Title' => $title, |
||
| 125 | 'ID:not' => $id, |
||
| 126 | ]); |
||
| 127 | /** @var DataObject $duplicateItem */ |
||
| 128 | foreach ($duplicateItems as $duplicateItem) { |
||
| 129 | $duplicateItem->delete(); |
||
| 130 | } |
||
| 131 | |||
| 132 | // Update progress bar |
||
| 133 | $done++; |
||
| 134 | $this->progress($done, $count); |
||
| 135 | } |
||
| 136 | |||
| 137 | $this->progress(""); |
||
| 138 | $this->progress("Completed cleaning duplicates for {$class}"); |
||
| 139 | } |
||
| 140 | } |
||
| 141 |