Passed
Push — v1 ( 0f87a2...543469 )
by Andrew
08:17 queued 04:56
created

ErrorSamples::deleteAllErrorSamples()   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 1
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
16
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...
17
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...
18
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...
19
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...
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 ErrorSamples extends Component
27
{
28
    // Constants
29
    // =========================================================================
30
31
    // Public Methods
32
    // =========================================================================
33
34
    /**
35
     * Get the total number of errors optionally limited by siteId
36
     *
37
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
38
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
39
     *
40
     * @return int|string
41
     */
42
    public function totalErrorSamples(int $siteId, string $column)
43
    {
44
        // Get the total number of errors
45
        $query = (new Query())
46
            ->from(['{{%webperf_error_samples}}'])
47
            ->where(['not', [$column => null]])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
48
            ;
49
        if ((int)$siteId !== 0) {
50
            $query->andWhere(['siteId' => $siteId]);
51
        }
52
53
        return $query->count();
54
    }
55
56
    /**
57
     * Get the page title from errors by URL and optionally siteId
58
     *
59
     * @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...
60
     * @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...
61
     *
62
     * @return string
63
     */
64
    public function pageTitle(string $url, int $siteId = 0): string
65
    {
66
        // Get the page title from a URL
67
        $query = (new Query())
68
            ->select(['title'])
69
            ->from(['{{%webperf_error_samples}}'])
70
            ->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...
71
                'and', ['url' => $url],
72
                ['not', ['title' => '']],
73
            ])
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...
74
        ;
75
        if ((int)$siteId !== 0) {
76
            $query->andWhere(['siteId' => $siteId]);
77
        }
78
        $result = $query->one();
79
        // Decode any emojis in the title
80
        if (!empty($result['title'])) {
81
            $result['title'] = html_entity_decode($result['title'], ENT_NOQUOTES, 'UTF-8');
82
        }
83
84
        return $result['title'] ?? '';
85
    }
86
87
    /**
88
     * Add an error to the webperf_error_samples table
89
     *
90
     * @param DbErrorSampleInterface $errorSample
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
91
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
92
    public function addErrorSample(DbErrorSampleInterface $errorSample)
93
    {
94
        // Validate the model before saving it to the db
95
        if ($errorSample->validate() === false) {
96
            Craft::error(
97
                Craft::t(
98
                    'webperf',
99
                    'Error validating error sample: {errors}',
100
                    ['errors' => print_r($errorSample->getErrors(), true)]
101
                ),
102
                __METHOD__
103
            );
104
105
            return;
106
        }
107
        // Get the validated model attributes and save them to the db
108
        $errorSampleConfig = $errorSample->getAttributes();
109
        if (!empty($errorSampleConfig['pageErrors'])) {
110
            if (\is_array($errorSampleConfig['pageErrors'])) {
111
                $errorSampleConfig['pageErrors'] = Json::encode($errorSampleConfig['pageErrors']);
112
            }
113
            $db = Craft::$app->getDb();
114
            Craft::debug('Creating new error sample', __METHOD__);
115
            // Create a new record
116
            try {
117
                $result = $db->createCommand()->insert(
118
                    '{{%webperf_error_samples}}',
119
                    $errorSampleConfig
120
                )->execute();
121
                Craft::debug($result, __METHOD__);
122
            } catch (\Exception $e) {
123
                Craft::error($e->getMessage(), __METHOD__);
124
            }
125
            // After adding the ErrorSample, trim the webperf_error_samples db table
126
            if (Webperf::$settings->automaticallyTrimErrorSamples) {
127
                $this->trimErrorSamples();
128
            }
129
        }
130
    }
131
132
    /**
133
     * Delete a error sample by id
134
     *
135
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
136
     *
137
     * @return int The result
138
     */
139
    public function deleteErrorSampleById(int $id): int
140
    {
141
        $db = Craft::$app->getDb();
142
        // Delete a row from the db table
143
        try {
144
            $result = $db->createCommand()->delete(
145
                '{{%webperf_error_samples}}',
146
                [
147
                    'id' => $id,
148
                ]
149
            )->execute();
150
        } catch (\Exception $e) {
151
            Craft::error($e->getMessage(), __METHOD__);
152
            $result = 0;
153
        }
154
155
        return $result;
156
    }
157
158
    /**
159
     * Delete error samples by URL and optionally siteId
160
     *
161
     * @param string   $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
162
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
163
     *
164
     * @return int
165
     */
166
    public function deleteErrorSamplesByUrl(string $url, int $siteId = null): int
167
    {
168
        $db = Craft::$app->getDb();
169
        // Delete a row from the db table
170
        try {
171
            $conditions = ['url' => $url];
172
            if ($siteId !== null) {
173
                $conditions['siteId'] = $siteId;
174
            }
175
            $result = $db->createCommand()->delete(
176
                '{{%webperf_error_samples}}',
177
                $conditions
178
            )->execute();
179
        } catch (\Exception $e) {
180
            Craft::error($e->getMessage(), __METHOD__);
181
            $result = 0;
182
        }
183
184
        return $result;
185
    }
186
187
    /**
188
     * Delete all error samples optionally siteId
189
     *
190
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
191
     *
192
     * @return int
193
     */
194
    public function deleteAllErrorSamples(int $siteId = null): int
195
    {
196
        $db = Craft::$app->getDb();
197
        // Delete a row from the db table
198
        try {
199
            $conditions = [];
200
            if ($siteId !== null) {
201
                $conditions['siteId'] = $siteId;
202
            }
203
            $result = $db->createCommand()->delete(
204
                '{{%webperf_error_samples}}',
205
                $conditions
206
            )->execute();
207
        } catch (\Exception $e) {
208
            Craft::error($e->getMessage(), __METHOD__);
209
            $result = 0;
210
        }
211
212
        return $result;
213
    }
214
215
    /**
216
     * Trim the webperf_error_samples db table based on the errorSamplesStoredLimit
217
     * config.php setting
218
     *
219
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
220
     *
221
     * @return int
222
     */
223
    public function trimErrorSamples(int $limit = null): int
224
    {
225
        $affectedRows = 0;
226
        $db = Craft::$app->getDb();
227
        $quotedTable = $db->quoteTableName('{{%webperf_error_samples}}');
228
        $limit = $limit ?? Webperf::$settings->errorSamplesStoredLimit;
229
230
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
231
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
232
            try {
233
                if ($db->getIsMysql()) {
234
                    // Handle MySQL
235
                    $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...
236
                        "
237
                        DELETE FROM {$quotedTable}
238
                        WHERE id NOT IN (
239
                          SELECT id
240
                          FROM (
241
                            SELECT id
242
                            FROM {$quotedTable}
243
                            ORDER BY dateCreated DESC
244
                            LIMIT {$limit}
245
                          ) foo
246
                        )
247
                        "
248
                    )->execute();
249
                }
250
                if ($db->getIsPgsql()) {
251
                    // Handle Postgres
252
                    $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...
253
                        "
254
                        DELETE FROM {$quotedTable}
255
                        WHERE id NOT IN (
256
                          SELECT id
257
                          FROM (
258
                            SELECT id
259
                            FROM {$quotedTable}
260
                            ORDER BY \"dateCreated\" DESC
261
                            LIMIT {$limit}
262
                          ) foo
263
                        )
264
                        "
265
                    )->execute();
266
                }
267
            } catch (\Exception $e) {
268
                Craft::error($e->getMessage(), __METHOD__);
269
            }
270
            Craft::info(
271
                Craft::t(
272
                    'webperf',
273
                    'Trimmed {rows} from webperf_error_samples table',
274
                    ['rows' => $affectedRows]
275
                ),
276
                __METHOD__
277
            );
278
        }
279
280
        return $affectedRows;
281
    }
282
}
283