Passed
Push — v1 ( 3980d8...7dfb05 )
by Andrew
12:06 queued 07:51
created

DataSamples::deleteDataSamplesByUrl()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 19
rs 9.8333
c 0
b 0
f 0
cc 3
nc 5
nop 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) 2019 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 nystudio107\webperf\Webperf;
14
use nystudio107\webperf\base\CraftDataSample;
15
use nystudio107\webperf\base\DbDataSampleInterface;
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
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...
20
21
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
22
 * @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...
23
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
24
 * @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...
25
 */
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...
26
class DataSamples extends Component
27
{
28
    // Constants
29
    // =========================================================================
30
31
    const OUTLIER_PAGELOAD_MULTIPLIER = 10;
32
33
    // Public Methods
34
    // =========================================================================
35
36
    /**
37
     * Get the total number of data samples optionally limited by siteId
38
     *
39
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
40
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
41
     *
42
     * @return int|string
43
     */
44
    public function totalSamples(int $siteId, string $column)
45
    {
46
        // Get the total number of data samples
47
        $query = (new Query())
48
            ->from(['{{%webperf_data_samples}}'])
49
            ->where(['not', [$column => null]])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
50
            ;
51
        if ((int)$siteId !== 0) {
52
            $query->andWhere(['siteId' => $siteId]);
53
        }
54
        return $query->count();
55
    }
56
57
    /**
58
     * Get the page title from data samples by URL and optionally siteId
59
     *
60
     * @param string   $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 1 spaces after parameter type; 3 found
Loading history...
61
     * @param int $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
62
     *
63
     * @return string
64
     */
65
    public function pageTitle(string $url, int $siteId = 0): string
66
    {
67
        // Get the page title from a URL
68
        $query = (new Query())
69
            ->select(['title'])
70
            ->from(['{{%webperf_data_samples}}'])
71
            ->where([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
72
                'and', ['url' => $url],
73
                ['not', ['title' => '']],
74
            ])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
75
        ;
76
        if ((int)$siteId !== 0) {
77
            $query->andWhere(['siteId' => $siteId]);
78
        }
79
        $result = $query->one();
80
        // Decode any emojis in the title
81
        if (!empty($result['title'])) {
82
            $result['title'] = html_entity_decode($result['title'], ENT_NOQUOTES, 'UTF-8');
83
        }
84
85
        return $result['title'] ?? '';
86
    }
87
88
    /**
89
     * Add a data sample to the webperf_data_samples table
90
     *
91
     * @param DbDataSampleInterface $dataSample
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
92
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
93
    public function addDataSample(DbDataSampleInterface $dataSample)
94
    {
95
        // Validate the model before saving it to the db
96
        if ($dataSample->validate() === false) {
97
            Craft::error(
98
                Craft::t(
99
                    'webperf',
100
                    'Error validating data sample: {errors}',
101
                    ['errors' => print_r($dataSample->getErrors(), true)]
102
                ),
103
                __METHOD__
104
            );
105
106
            return;
107
        }
108
        $isNew = true;
109
        if (!empty($dataSample->requestId)) {
0 ignored issues
show
Bug introduced by
Accessing requestId on the interface nystudio107\webperf\base\DbDataSampleInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
110
            // See if a data sample exists with the same requestId already
111
            $testSample = (new Query())
112
                ->from(['{{%webperf_data_samples}}'])
113
                ->where(['requestId' => $dataSample->requestId])
114
                ->one();
115
            // If it exists, update it rather than having duplicates
116
            if (!empty($testSample)) {
117
                $isNew = false;
118
            }
119
        }
120
        // Get the validated model attributes and save them to the db
121
        $dataSampleConfig = $dataSample->getAttributes();
122
        $db = Craft::$app->getDb();
123
        if ($isNew) {
124
            Craft::debug('Creating new data sample', __METHOD__);
125
            // Create a new record
126
            try {
127
                $result = $db->createCommand()->insert(
128
                    '{{%webperf_data_samples}}',
129
                    $dataSampleConfig
130
                )->execute();
131
                Craft::debug($result, __METHOD__);
132
            } catch (\Exception $e) {
133
                Craft::error($e->getMessage(), __METHOD__);
134
            }
135
        } else {
136
            Craft::debug('Updating existing data sample', __METHOD__);
137
            // Update the existing record
138
            try {
139
                $result = $db->createCommand()->update(
140
                    '{{%webperf_data_samples}}',
141
                    $dataSampleConfig,
142
                    [
143
                        'requestId' => $dataSample->requestId,
144
                    ]
145
                )->execute();
146
                Craft::debug($result, __METHOD__);
147
            } catch (\Exception $e) {
148
                Craft::error($e->getMessage(), __METHOD__);
149
            }
150
        }
151
        // Trim orphaned samples
152
        $this->trimOrphanedSamples($dataSample->requestId);
153
        // After adding the DataSample, trim the webperf_data_samples db table
154
        if (Webperf::$settings->automaticallyTrimDataSamples) {
155
            $this->trimDataSamples();
156
        }
157
    }
158
159
    /**
160
     * Delete a data sample by id
161
     *
162
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
163
     *
164
     * @return int The result
165
     */
166
    public function deleteSampleById(int $id): int
167
    {
168
        $db = Craft::$app->getDb();
169
        // Delete a row from the db table
170
        try {
171
            $result = $db->createCommand()->delete(
172
                '{{%webperf_data_samples}}',
173
                [
174
                    'id' => $id,
175
                ]
176
            )->execute();
177
        } catch (\Exception $e) {
178
            Craft::error($e->getMessage(), __METHOD__);
179
            $result = 0;
180
        }
181
182
        return $result;
183
    }
184
185
    /**
186
     * Delete data samples by URL and optionally siteId
187
     *
188
     * @param string   $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
189
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
190
     *
191
     * @return int
192
     */
193
    public function deleteDataSamplesByUrl(string $url, int $siteId = null): int
194
    {
195
        $db = Craft::$app->getDb();
196
        // Delete a row from the db table
197
        try {
198
            $conditions = ['url' => $url];
199
            if ($siteId !== null) {
200
                $conditions['siteId'] = $siteId;
201
            }
202
            $result = $db->createCommand()->delete(
203
                '{{%webperf_data_samples}}',
204
                $conditions
205
            )->execute();
206
        } catch (\Exception $e) {
207
            Craft::error($e->getMessage(), __METHOD__);
208
            $result = 0;
209
        }
210
211
        return $result;
212
    }
213
214
    /**
215
     * Delete data all samples optionally siteId
216
     *
217
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
218
     *
219
     * @return int
220
     */
221
    public function deleteAllDataSamples(int $siteId = null): int
222
    {
223
        $db = Craft::$app->getDb();
224
        // Delete a row from the db table
225
        try {
226
            $conditions = [];
227
            if ($siteId !== null) {
228
                $conditions['siteId'] = $siteId;
229
            }
230
            $result = $db->createCommand()->delete(
231
                '{{%webperf_data_samples}}',
232
                $conditions
233
            )->execute();
234
        } catch (\Exception $e) {
235
            Craft::error($e->getMessage(), __METHOD__);
236
            $result = 0;
237
        }
238
239
        return $result;
240
    }
241
242
    /**
243
     * Trim any samples that our outliers
244
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
245
    public function trimOutlierSamples()
246
    {
247
        if (Webperf::$settings->trimOutlierDataSamples) {
248
            $db = Craft::$app->getDb();
249
            Craft::debug('Trimming outlier samples', __METHOD__);
250
            if ($db->getIsMysql()) {
251
                // Get the average pageload time
252
                $stats = (new Query())
253
                    ->from('{{%webperf_data_samples}}')
254
                    ->select([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
255
                        'AVG(pageLoad) AS avg',
256
                    ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
257
                    ->one();
258
            }
259
            if ($db->getIsPgsql()) {
260
                // Get the average pageload time
261
                $stats = (new Query())
262
                    ->from('{{%webperf_data_samples}}')
263
                    ->select([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
264
                        'AVG("pageLoad") AS avg',
265
                    ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
266
                    ->one();
267
            }
268
            if (!empty($stats['avg'])) {
269
                $threshold = $stats['avg'] * self::OUTLIER_PAGELOAD_MULTIPLIER;
270
                // Delete any samples that are far above average
271
                try {
272
                    $result = $db->createCommand()->delete(
273
                        '{{%webperf_data_samples}}',
274
                        ['>', 'pageLoad', $threshold]
275
                    )->execute();
276
                    Craft::debug($result, __METHOD__);
277
                } catch (\Exception $e) {
278
                    Craft::error($e->getMessage(), __METHOD__);
279
                }
280
            }
281
        }
282
    }
283
284
    /**
285
     * Trim samples that have the placeholder in the URL, aka they never
286
     * received the Boomerang beacon
287
     *
288
     * @param int $requestId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
289
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
290
    public function trimOrphanedSamples($requestId)
291
    {
292
        $db = Craft::$app->getDb();
293
        Craft::debug('Trimming orphaned samples', __METHOD__);
294
        // Update the existing record
295
        try {
296
            $result = $db->createCommand()->delete(
297
                '{{%webperf_data_samples}}',
298
                [
299
                    'and', ['url' => CraftDataSample::PLACEHOLDER_URL],
300
                    ['not', ['requestId' => $requestId]],
301
                ]
302
            )->execute();
303
            Craft::debug($result, __METHOD__);
304
        } catch (\Exception $e) {
305
            Craft::error($e->getMessage(), __METHOD__);
306
        }
307
    }
308
309
    /**
310
     * Trim the webperf_data_samples db table based on the dataSamplesStoredLimit
311
     * config.php setting
312
     *
313
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
314
     *
315
     * @return int
316
     */
317
    public function trimDataSamples(int $limit = null): int
318
    {
319
        $this->trimOutlierSamples();
320
        $affectedRows = 0;
321
        $db = Craft::$app->getDb();
322
        $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}');
323
        $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit;
324
325
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
326
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
327
            try {
328
                if ($db->getIsMysql()) {
329
                    // Handle MySQL
330
                    $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...
331
                        "
332
                        DELETE FROM {$quotedTable}
333
                        WHERE id NOT IN (
334
                          SELECT id
335
                          FROM (
336
                            SELECT id
337
                            FROM {$quotedTable}
338
                            ORDER BY dateCreated DESC
339
                            LIMIT {$limit}
340
                          ) foo
341
                        )
342
                        "
343
                    )->execute();
344
                }
345
                if ($db->getIsPgsql()) {
346
                    // Handle Postgres
347
                    $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...
348
                        "
349
                        DELETE FROM {$quotedTable}
350
                        WHERE id NOT IN (
351
                          SELECT id
352
                          FROM (
353
                            SELECT id
354
                            FROM {$quotedTable}
355
                            ORDER BY \"dateCreated\" DESC
356
                            LIMIT {$limit}
357
                          ) foo
358
                        )
359
                        "
360
                    )->execute();
361
                }
362
            } catch (\Exception $e) {
363
                Craft::error($e->getMessage(), __METHOD__);
364
            }
365
            Craft::info(
366
                Craft::t(
367
                    'webperf',
368
                    'Trimmed {rows} from webperf_data_samples table',
369
                    ['rows' => $affectedRows]
370
                ),
371
                __METHOD__
372
            );
373
        }
374
375
        return $affectedRows;
376
    }
377
}
378