Passed
Push — v1 ( 83a102...fe1757 )
by Andrew
11:33 queued 04:25
created

ErrorSamples::rateLimited()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 0
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\DbErrorSampleInterface;
15
use nystudio107\webperf\events\ErrorSampleEvent;
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
use craft\helpers\Json;
0 ignored issues
show
Bug introduced by
The type craft\helpers\Json 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...
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @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 for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
24
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @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 for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
26
 */
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...
27
class ErrorSamples extends Component
28
{
29
    // Constants
30
    // =========================================================================
31
32
    const LAST_ERRORSAMPLES_TRIM_CACHE_KEY = 'webperf-last-errorsamples-trim';
33
34
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
35
     * @event ErrorSampleEvent The event that is triggered before the error sample is saved
36
     * You may set [[ErrorSampleEvent::isValid]] to `false` to prevent the error sample from getting saved.
37
     *
38
     * ```php
39
     * use nystudio107\webperf\services\ErrorSamples;
40
     * use nystudio107\retour\events\ErrorSampleEvent;
41
     *
42
     * Event::on(ErrorSamples::class,
43
     *     ErrorSamples::EVENT_BEFORE_SAVE_ERROR_SAMPLE,
44
     *     function(ErrorSampleEvent $event) {
45
     *         // potentially set $event->isValid;
46
     *     }
47
     * );
48
     * ```
49
     */
50
    const EVENT_BEFORE_SAVE_ERROR_SAMPLE = 'beforeSaveErrorSample';
51
52
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
53
     * @event ErrorSampleEvent The event that is triggered after the redirect is saved
54
     *
55
     * ```php
56
     * use nystudio107\webperf\services\ErrorSamples;
57
     * use nystudio107\webperf\events\ErrorSampleEvent;
58
     *
59
     * Event::on(ErrorSamples::class,
60
     *     ErrorSamples::EVENT_AFTER_SAVE_ERROR_SAMPLE,
61
     *     function(ErrorSampleEvent $event) {
62
     *         // the error sample was saved
63
     *     }
64
     * );
65
     * ```
66
     */
67
    const EVENT_AFTER_SAVE_ERROR_SAMPLE = 'afterSaveErrorSample';
68
69
    // Public Methods
70
    // =========================================================================
71
72
    /**
73
     * Get the total number of errors optionally limited by siteId
74
     *
75
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
76
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
77
     *
78
     * @return int|string
79
     */
80
    public function totalErrorSamples(int $siteId, string $column)
81
    {
82
        // Get the total number of errors
83
        $query = (new Query())
84
            ->from(['{{%webperf_error_samples}}'])
85
            ->where(['not', [$column => null]])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
86
            ;
87
        if ((int)$siteId !== 0) {
88
            $query->andWhere(['siteId' => $siteId]);
89
        }
90
91
        return $query->count();
92
    }
93
94
    /**
95
     * Get the total number of errors optionally limited by siteId, between
96
     * $start and $end
97
     *
98
     * @param int         $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
99
     * @param string      $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
100
     * @param string      $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
101
     * @param string|null $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
102
     * @param string|null $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
103
     *
104
     * @return int
105
     */
106
    public function totalErrorSamplesRange(int $siteId, string $start, string $end, $pageUrl = null, $type = null): int
107
    {
108
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
109
        $end = date('Y-m-d', strtotime($end.'+1 day'));
110
        // Get the total number of errors
111
        $query = (new Query())
112
            ->from(['{{%webperf_error_samples}}'])
113
            ->where(['between', 'dateCreated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
114
        ;
115
        if ($type !== null) {
116
            $query
117
                ->andWhere(['type' => $type])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
118
            ;
119
        }
120
        if ($pageUrl !== null) {
121
            $query
122
                ->andWhere(['url' => $pageUrl])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
123
            ;
124
        }
125
        if ((int)$siteId !== 0) {
126
            $query->andWhere(['siteId' => $siteId]);
127
        }
128
129
        return $query->count();
130
    }
131
132
    /**
133
     * Get the page title from errors by URL and optionally siteId
134
     *
135
     * @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...
136
     * @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...
137
     *
138
     * @return string
139
     */
140
    public function pageTitle(string $url, int $siteId = 0): string
141
    {
142
        // Get the page title from a URL
143
        $query = (new Query())
144
            ->select(['title'])
145
            ->from(['{{%webperf_error_samples}}'])
146
            ->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...
147
                'and', ['url' => $url],
148
                ['not', ['title' => '']],
149
            ])
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...
150
        ;
151
        if ((int)$siteId !== 0) {
152
            $query->andWhere(['siteId' => $siteId]);
153
        }
154
        $result = $query->one();
155
        // Decode any emojis in the title
156
        if (!empty($result['title'])) {
157
            $result['title'] = html_entity_decode($result['title'], ENT_NOQUOTES, 'UTF-8');
158
        }
159
160
        return $result['title'] ?? '';
161
    }
162
163
    /**
164
     * Add an error to the webperf_error_samples table
165
     *
166
     * @param DbErrorSampleInterface $errorSample
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
167
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
168
    public function addErrorSample(DbErrorSampleInterface $errorSample)
169
    {
170
        // Validate the model before saving it to the db
171
        if ($errorSample->validate() === false) {
172
            Craft::error(
173
                Craft::t(
174
                    'webperf',
175
                    'Error validating error sample: {errors}',
176
                    ['errors' => print_r($errorSample->getErrors(), true)]
177
                ),
178
                __METHOD__
179
            );
180
181
            return;
182
        }
183
        // Trigger a 'beforeSaveErrorSample' event
184
        $event = new ErrorSampleEvent([
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...
185
            'errorSample' => $errorSample,
186
        ]);
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...
187
        $this->trigger(self::EVENT_BEFORE_SAVE_ERROR_SAMPLE, $event);
188
        if (!$event->isValid) {
189
            return;
190
        }
191
        // Get the validated model attributes and save them to the db
192
        $errorSampleConfig = $errorSample->getAttributes();
193
        if (!empty($errorSampleConfig['pageErrors'])) {
194
            if (\is_array($errorSampleConfig['pageErrors'])) {
195
                $errorSampleConfig['pageErrors'] = Json::encode($errorSampleConfig['pageErrors']);
196
            }
197
            $db = Craft::$app->getDb();
198
            Craft::debug('Creating new error sample', __METHOD__);
199
            // Create a new record
200
            try {
201
                $result = $db->createCommand()->insert(
202
                    '{{%webperf_error_samples}}',
203
                    $errorSampleConfig
204
                )->execute();
205
                Craft::debug($result, __METHOD__);
206
            } catch (\Exception $e) {
207
                Craft::error($e->getMessage(), __METHOD__);
208
            }
209
            // Trigger a 'afterSaveErrorSample' event
210
            $this->trigger(self::EVENT_AFTER_SAVE_ERROR_SAMPLE, $event);
211
            // After adding the ErrorSample, trim the webperf_error_samples db table
212
            if (Webperf::$settings->automaticallyTrimErrorSamples && !$this->rateLimited()) {
213
                $this->trimErrorSamples();
214
            }
215
        }
216
    }
217
218
    /**
219
     * Delete a error sample by id
220
     *
221
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
222
     *
223
     * @return int The result
224
     */
225
    public function deleteErrorSampleById(int $id): int
226
    {
227
        $db = Craft::$app->getDb();
228
        // Delete a row from the db table
229
        try {
230
            $result = $db->createCommand()->delete(
231
                '{{%webperf_error_samples}}',
232
                [
233
                    'id' => $id,
234
                ]
235
            )->execute();
236
        } catch (\Exception $e) {
237
            Craft::error($e->getMessage(), __METHOD__);
238
            $result = 0;
239
        }
240
241
        return $result;
242
    }
243
244
    /**
245
     * Delete error samples by URL and optionally siteId
246
     *
247
     * @param string   $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
248
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
249
     *
250
     * @return int
251
     */
252
    public function deleteErrorSamplesByUrl(string $url, int $siteId = null): int
253
    {
254
        $db = Craft::$app->getDb();
255
        // Delete a row from the db table
256
        try {
257
            $conditions = ['url' => $url];
258
            if ($siteId !== null) {
259
                $conditions['siteId'] = $siteId;
260
            }
261
            $result = $db->createCommand()->delete(
262
                '{{%webperf_error_samples}}',
263
                $conditions
264
            )->execute();
265
        } catch (\Exception $e) {
266
            Craft::error($e->getMessage(), __METHOD__);
267
            $result = 0;
268
        }
269
270
        return $result;
271
    }
272
273
    /**
274
     * Delete all error samples optionally siteId
275
     *
276
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
277
     *
278
     * @return int
279
     */
280
    public function deleteAllErrorSamples(int $siteId = null): int
281
    {
282
        $db = Craft::$app->getDb();
283
        // Delete a row from the db table
284
        try {
285
            $conditions = [];
286
            if ($siteId !== null) {
287
                $conditions['siteId'] = $siteId;
288
            }
289
            $result = $db->createCommand()->delete(
290
                '{{%webperf_error_samples}}',
291
                $conditions
292
            )->execute();
293
        } catch (\Exception $e) {
294
            Craft::error($e->getMessage(), __METHOD__);
295
            $result = 0;
296
        }
297
298
        return $result;
299
    }
300
301
    /**
302
     * Trim the webperf_error_samples db table based on the errorSamplesStoredLimit
303
     * config.php setting
304
     *
305
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
306
     *
307
     * @return int
308
     */
309
    public function trimErrorSamples(int $limit = null): int
310
    {
311
        $affectedRows = 0;
312
        $db = Craft::$app->getDb();
313
        $quotedTable = $db->quoteTableName('{{%webperf_error_samples}}');
314
        $limit = $limit ?? Webperf::$settings->errorSamplesStoredLimit;
315
316
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
317
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
318
            try {
319
                if ($db->getIsMysql()) {
320
                    // Handle MySQL
321
                    $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...
322
                        "
323
                        DELETE FROM {$quotedTable}
324
                        WHERE id NOT IN (
325
                          SELECT id
326
                          FROM (
327
                            SELECT id
328
                            FROM {$quotedTable}
329
                            ORDER BY dateCreated DESC
330
                            LIMIT {$limit}
331
                          ) foo
332
                        )
333
                        "
334
                    )->execute();
335
                }
336
                if ($db->getIsPgsql()) {
337
                    // Handle Postgres
338
                    $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...
339
                        "
340
                        DELETE FROM {$quotedTable}
341
                        WHERE id NOT IN (
342
                          SELECT id
343
                          FROM (
344
                            SELECT id
345
                            FROM {$quotedTable}
346
                            ORDER BY \"dateCreated\" DESC
347
                            LIMIT {$limit}
348
                          ) foo
349
                        )
350
                        "
351
                    )->execute();
352
                }
353
            } catch (\Exception $e) {
354
                Craft::error($e->getMessage(), __METHOD__);
355
            }
356
            Craft::info(
357
                Craft::t(
358
                    'webperf',
359
                    'Trimmed {rows} from webperf_error_samples table',
360
                    ['rows' => $affectedRows]
361
                ),
362
                __METHOD__
363
            );
364
        }
365
366
        return $affectedRows;
367
    }
368
369
370
    // Protected Methods
371
    // =========================================================================
372
373
    /**
374
     * Don't trim more than a given interval, so that performance is not affected
375
     *
376
     * @return bool
377
     */
378
    protected function rateLimited(): bool
379
    {
380
        $limited = false;
381
        $now = round(microtime(true) * 1000);
382
        $cache = Craft::$app->getCache();
383
        $then = $cache->get(self::LAST_ERRORSAMPLES_TRIM_CACHE_KEY);
384
        if (($then !== false) && ($now - (int)$then < Webperf::$settings->samplesRateLimitMs)) {
385
            $limited = true;
386
        }
387
        $cache->set(self::LAST_ERRORSAMPLES_TRIM_CACHE_KEY, $now, 0);
388
389
        return $limited;
390
    }
391
}
392