Passed
Push — develop ( 740953...5aeb44 )
by Andrew
03:29
created

ErrorSamples::totalErrorSamplesRange()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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