Passed
Push — develop ( 807500...06cb94 )
by Andrew
05:12
created

DataSamples   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 16
eloc 86
dl 0
loc 182
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B addDataSample() 0 59 7
A trimOrphanedSamples() 0 16 2
A trimDataSamples() 0 58 5
A totalSamples() 0 11 2
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
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
31
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
32
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
33
     *
34
     * @return int|string
35
     */
36
    public function totalSamples(int $siteId, string $column)
37
    {
38
        // See if a redirect exists with this source URL already
39
        $query = (new Query())
40
            ->from(['{{%webperf_data_samples}}'])
41
            ->where(['not', [$column => null]])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
42
            ;
43
        if ((int)$siteId !== 0) {
44
            $query->andWhere(['siteId' => $siteId]);
45
        }
46
        return $query->count();
47
    }
48
49
    /**
50
     * Add a data sample to the webperf_data_samples table
51
     *
52
     * @param DataSample $dataSample
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
53
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
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
        }
114
    }
115
116
    /**
117
     * Trim samples that have the placeholder in the URL, aka they never
118
     * received the Boomerang beacon
119
     *
120
     * @param int $requestId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
121
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
122
    public function trimOrphanedSamples(int $requestId)
123
    {
124
        $db = Craft::$app->getDb();
125
        Craft::debug('Trimming orphaned samples', __METHOD__);
126
        // Update the existing record
127
        try {
128
            $result = $db->createCommand()->delete(
129
                '{{%webperf_data_samples}}',
130
                [
131
                    'and', ['url' => DataSample::PLACEHOLDER_URL],
132
                    ['not', ['requestId' => $requestId]],
133
                ]
134
            )->execute();
135
            Craft::debug($result, __METHOD__);
136
        } catch (\Exception $e) {
137
            Craft::error($e->getMessage(), __METHOD__);
138
        }
139
    }
140
141
    /**
142
     * Trim the webperf_data_samples db table based on the dataSamplesStoredLimit
143
     * config.php setting
144
     *
145
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
146
     *
147
     * @return int
148
     */
149
    public function trimDataSamples(int $limit = null): int
150
    {
151
        $affectedRows = 0;
152
        $db = Craft::$app->getDb();
153
        $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}');
154
        $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit;
155
156
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
157
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
158
            try {
159
                if ($db->getIsMysql()) {
160
                    // Handle MySQL
161
                    $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...
162
                        "
163
                        DELETE FROM {$quotedTable}
164
                        WHERE id NOT IN (
165
                          SELECT id
166
                          FROM (
167
                            SELECT id
168
                            FROM {$quotedTable}
169
                            ORDER BY dateUpdated DESC
170
                            LIMIT {$limit}
171
                          ) foo
172
                        )
173
                        "
174
                    )->execute();
175
                }
176
                if ($db->getIsPgsql()) {
177
                    // Handle Postgres
178
                    $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...
179
                        "
180
                        DELETE FROM {$quotedTable}
181
                        WHERE id NOT IN (
182
                          SELECT id
183
                          FROM (
184
                            SELECT id
185
                            FROM {$quotedTable}
186
                            ORDER BY \"dateUpdated\" DESC
187
                            LIMIT {$limit}
188
                          ) foo
189
                        )
190
                        "
191
                    )->execute();
192
                }
193
            } catch (\Exception $e) {
194
                Craft::error($e->getMessage(), __METHOD__);
195
            }
196
            Craft::info(
197
                Craft::t(
198
                    'webperf',
199
                    'Trimmed {rows} from webperf_data_samples table',
200
                    ['rows' => $affectedRows]
201
                ),
202
                __METHOD__
203
            );
204
        }
205
206
        return $affectedRows;
207
    }
208
}
209