| 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 |
||
| 70 | public function trimDataSamples(int $limit = null): int |
||
| 71 | { |
||
| 72 | $affectedRows = 0; |
||
| 73 | $db = Craft::$app->getDb(); |
||
| 74 | $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}'); |
||
| 75 | $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit; |
||
| 76 | |||
| 77 | if ($limit !== null) { |
||
| 78 | // https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n |
||
| 79 | try { |
||
| 80 | if ($db->getIsMysql()) { |
||
| 81 | // Handle MySQL |
||
| 82 | $affectedRows = $db->createCommand(/** @lang mysql */ |
||
| 83 | " |
||
| 84 | DELETE FROM {$quotedTable} |
||
| 85 | WHERE id NOT IN ( |
||
| 86 | SELECT id |
||
| 87 | FROM ( |
||
| 88 | SELECT id |
||
| 89 | FROM {$quotedTable} |
||
| 90 | ORDER BY hitLastTime DESC |
||
| 91 | LIMIT {$limit} |
||
| 92 | ) foo |
||
| 93 | ) |
||
| 94 | " |
||
| 95 | )->execute(); |
||
| 96 | } |
||
| 97 | if ($db->getIsPgsql()) { |
||
| 98 | // Handle Postgres |
||
| 99 | $affectedRows = $db->createCommand(/** @lang mysql */ |
||
| 100 | " |
||
| 101 | DELETE FROM {$quotedTable} |
||
| 102 | WHERE id NOT IN ( |
||
| 103 | SELECT id |
||
| 104 | FROM ( |
||
| 105 | SELECT id |
||
| 106 | FROM {$quotedTable} |
||
| 107 | ORDER BY \"hitLastTime\" DESC |
||
| 108 | LIMIT {$limit} |
||
| 109 | ) foo |
||
| 110 | ) |
||
| 111 | " |
||
| 112 | )->execute(); |
||
| 113 | } |
||
| 114 | } catch (\Exception $e) { |
||
| 115 | Craft::error($e->getMessage(), __METHOD__); |
||
| 116 | } |
||
| 117 | Craft::info( |
||
| 118 | Craft::t( |
||
| 119 | 'webperf', |
||
| 120 | 'Trimmed {rows} from webperf_data_samples table', |
||
| 121 | ['rows' => $affectedRows] |
||
| 122 | ), |
||
| 123 | __METHOD__ |
||
| 124 | ); |
||
| 125 | } |
||
| 126 | |||
| 127 | return $affectedRows; |
||
| 128 | } |
||
| 130 |