| 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 |
||
| 54 | public function addDataSample(DataSample $dataSample) |
||
| 55 | { |
||
| 56 | // Validate the model before saving it to the db |
||
| 57 | if ($dataSample->validate() === false) { |
||
| 58 | Craft::error( |
||
| 59 | Craft::t( |
||
| 60 | 'webperf', |
||
| 61 | 'Error validating data sample: {errors}', |
||
| 62 | ['errors' => print_r($dataSample->getErrors(), true)] |
||
| 63 | ), |
||
| 64 | __METHOD__ |
||
| 65 | ); |
||
| 66 | |||
| 67 | return; |
||
| 68 | } |
||
| 69 | $isNew = true; |
||
| 70 | // See if a redirect exists with this source URL already |
||
| 71 | $testSample = (new Query()) |
||
| 72 | ->from(['{{%webperf_data_samples}}']) |
||
| 73 | ->where(['requestId' => $dataSample->requestId]) |
||
| 74 | ->one(); |
||
| 75 | // If it exists, update it rather than having duplicates |
||
| 76 | if (!empty($testSample)) { |
||
| 77 | $isNew = false; |
||
| 78 | } |
||
| 79 | // Get the validated model attributes and save them to the db |
||
| 80 | $dataSampleConfig = $dataSample->getAttributes($dataSample->fields()); |
||
| 81 | $db = Craft::$app->getDb(); |
||
| 82 | if ($isNew) { |
||
| 83 | Craft::debug('Creating new data sample', __METHOD__); |
||
| 84 | // Create a new record |
||
| 85 | try { |
||
| 86 | $db->createCommand()->insert( |
||
| 87 | '{{%webperf_data_samples}}', |
||
| 88 | $dataSampleConfig |
||
| 89 | )->execute(); |
||
| 90 | } catch (\Exception $e) { |
||
| 91 | Craft::error($e->getMessage(), __METHOD__); |
||
| 92 | } |
||
| 93 | } else { |
||
| 94 | Craft::debug('Updating existing data sample', __METHOD__); |
||
| 95 | // Update the existing record |
||
| 96 | try { |
||
| 97 | $db->createCommand()->update( |
||
| 98 | '{{%webperf_data_samples}}', |
||
| 99 | $dataSampleConfig, |
||
| 100 | [ |
||
| 101 | 'requestId' => $dataSample->requestId, |
||
| 102 | ] |
||
| 103 | )->execute(); |
||
| 104 | } catch (\Exception $e) { |
||
| 105 | Craft::error($e->getMessage(), __METHOD__); |
||
| 106 | } |
||
| 107 | } |
||
| 108 | // Trim orphaned samples |
||
| 109 | $this->trimOrphanedSamples($dataSample->requestId); |
||
| 110 | // After adding the DataSample, trim the webperf_data_samples db table |
||
| 111 | if (Webperf::$settings->automaticallyTrimDataSamples) { |
||
| 112 | $this->trimDataSamples(); |
||
| 113 | } |
||
| 209 |