Passed
Push — develop ( 5d2df0...c2b52a )
by Andrew
04:09
created

DataSamples::addDataSample()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 57
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 57
rs 8.3786
c 0
b 0
f 0
cc 7
nc 17
nop 1

How to fix   Long Method   

Long Method

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:

1
<?php
2
/**
3
 * Webperf plugin for Craft CMS 3.x
4
 *
5
 * Monitor the performance of your webpages through real-world user timing data
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2018 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\webperf\services;
12
13
use craft\db\Query;
0 ignored issues
show
Bug introduced by
The type craft\db\Query was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use nystudio107\webperf\Webperf;
15
use nystudio107\webperf\models\DataSample;
16
17
use Craft;
0 ignored issues
show
Bug introduced by
The type Craft was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use craft\base\Component;
0 ignored issues
show
Bug introduced by
The type craft\base\Component was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
21
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 4
Loading history...
22
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
23
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 3 spaces but found 5
Loading history...
24
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
25
class DataSamples extends Component
26
{
27
    // Public Methods
28
    // =========================================================================
29
30
    public function addDataSample(DataSample $dataSample)
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
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
        // After adding the DataSample, trim the webperf_data_samples db table
85
        if (Webperf::$settings->automaticallyTrimDataSamples) {
86
            $this->trimDataSamples();
87
        }
88
    }
89
90
    /**
91
     * Trim the webperf_data_samples db table based on the dataSamplesStoredLimit
92
     * config.php setting
93
     *
94
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
95
     *
96
     * @return int
97
     */
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) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
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 */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
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 */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
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
    }
157
}
158