| Conditions | 5 |
| Paths | 11 |
| Total Lines | 58 |
| Code Lines | 29 |
| 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 |
||
| 98 | public function trimDataSamples(int $limit = null): int |
||
| 99 | { |
||
| 100 | $affectedRows = 0; |
||
| 101 | $db = Craft::$app->getDb(); |
||
| 102 | $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}'); |
||
| 103 | $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit; |
||
| 104 | |||
| 105 | if ($limit !== null) { |
||
| 106 | // https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n |
||
| 107 | try { |
||
| 108 | if ($db->getIsMysql()) { |
||
| 109 | // Handle MySQL |
||
| 110 | $affectedRows = $db->createCommand(/** @lang mysql */ |
||
| 111 | " |
||
| 112 | DELETE FROM {$quotedTable} |
||
| 113 | WHERE id NOT IN ( |
||
| 114 | SELECT id |
||
| 115 | FROM ( |
||
| 116 | SELECT id |
||
| 117 | FROM {$quotedTable} |
||
| 118 | ORDER BY dateUpdated DESC |
||
| 119 | LIMIT {$limit} |
||
| 120 | ) foo |
||
| 121 | ) |
||
| 122 | " |
||
| 123 | )->execute(); |
||
| 124 | } |
||
| 125 | if ($db->getIsPgsql()) { |
||
| 126 | // Handle Postgres |
||
| 127 | $affectedRows = $db->createCommand(/** @lang mysql */ |
||
| 128 | " |
||
| 129 | DELETE FROM {$quotedTable} |
||
| 130 | WHERE id NOT IN ( |
||
| 131 | SELECT id |
||
| 132 | FROM ( |
||
| 133 | SELECT id |
||
| 134 | FROM {$quotedTable} |
||
| 135 | ORDER BY \"dateUpdated\" DESC |
||
| 136 | LIMIT {$limit} |
||
| 137 | ) foo |
||
| 138 | ) |
||
| 139 | " |
||
| 140 | )->execute(); |
||
| 141 | } |
||
| 142 | } catch (\Exception $e) { |
||
| 143 | Craft::error($e->getMessage(), __METHOD__); |
||
| 144 | } |
||
| 145 | Craft::info( |
||
| 146 | Craft::t( |
||
| 147 | 'webperf', |
||
| 148 | 'Trimmed {rows} from webperf_data_samples table', |
||
| 149 | ['rows' => $affectedRows] |
||
| 150 | ), |
||
| 151 | __METHOD__ |
||
| 152 | ); |
||
| 153 | } |
||
| 154 | |||
| 155 | return $affectedRows; |
||
| 156 | } |
||
| 158 |