| Conditions | 7 |
| Paths | 17 |
| Total Lines | 59 |
| Code Lines | 39 |
| 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 |
||
| 30 | public function addDataSample(DataSample $dataSample) |
||
| 31 | { |
||
| 32 | // Validate the model before saving it to the db |
||
| 33 | if ($dataSample->validate() === false) { |
||
| 34 | Craft::error( |
||
| 35 | Craft::t( |
||
| 36 | 'webperf', |
||
| 37 | 'Error validating data sample: {errors}', |
||
| 38 | ['errors' => print_r($dataSample->getErrors(), true)] |
||
| 39 | ), |
||
| 40 | __METHOD__ |
||
| 41 | ); |
||
| 42 | |||
| 43 | return; |
||
| 44 | } |
||
| 45 | $isNew = true; |
||
| 46 | // See if a redirect exists with this source URL already |
||
| 47 | $testSample = (new Query()) |
||
| 48 | ->from(['{{%webperf_data_samples}}']) |
||
| 49 | ->where(['requestId' => $dataSample->requestId]) |
||
| 50 | ->one(); |
||
| 51 | // If it exists, update it rather than having duplicates |
||
| 52 | if (!empty($testSample)) { |
||
| 53 | $isNew = false; |
||
| 54 | } |
||
| 55 | // Get the validated model attributes and save them to the db |
||
| 56 | $dataSampleConfig = $dataSample->getAttributes($dataSample->fields()); |
||
| 57 | $db = Craft::$app->getDb(); |
||
| 58 | if ($isNew) { |
||
| 59 | Craft::debug('Creating new data sample', __METHOD__); |
||
| 60 | // Create a new record |
||
| 61 | try { |
||
| 62 | $db->createCommand()->insert( |
||
| 63 | '{{%webperf_data_samples}}', |
||
| 64 | $dataSampleConfig |
||
| 65 | )->execute(); |
||
| 66 | } catch (\Exception $e) { |
||
| 67 | Craft::error($e->getMessage(), __METHOD__); |
||
| 68 | } |
||
| 69 | } else { |
||
| 70 | Craft::debug('Updating existing data sample', __METHOD__); |
||
| 71 | // Update the existing record |
||
| 72 | try { |
||
| 73 | $db->createCommand()->update( |
||
| 74 | '{{%webperf_data_samples}}', |
||
| 75 | $dataSampleConfig, |
||
| 76 | [ |
||
| 77 | 'requestId' => $dataSample->requestId, |
||
| 78 | ] |
||
| 79 | )->execute(); |
||
| 80 | } catch (\Exception $e) { |
||
| 81 | Craft::error($e->getMessage(), __METHOD__); |
||
| 82 | } |
||
| 83 | } |
||
| 84 | // Trim orphaned samples |
||
| 85 | $this->trimOrphanedSamples($dataSample->requestId); |
||
| 86 | // After adding the DataSample, trim the webperf_data_samples db table |
||
| 87 | if (Webperf::$settings->automaticallyTrimDataSamples) { |
||
| 88 | $this->trimDataSamples(); |
||
| 89 | } |
||
| 184 |