Passed
Push — develop ( c2b52a...7780c4 )
by Andrew
04:25
created

DataSamples::trimOrphanedSamples()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
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) 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
    public function addDataSample(DataSample $dataSample)
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
31
    {
32
        // Validate the model before saving it to the db
33
        if ($dataSample->validate() === false) {
34
            Craft::error(
35
                Craft::t(
36
                    'webperf',
37
                    'Error validating data sample: {errors}',
38
                    ['errors' => print_r($dataSample->getErrors(), true)]
39
                ),
40
                __METHOD__
41
            );
42
43
            return;
44
        }
45
        $isNew = true;
46
        // See if a redirect exists with this source URL already
47
        $testSample = (new Query())
48
            ->from(['{{%webperf_data_samples}}'])
49
            ->where(['requestId' => $dataSample->requestId])
50
            ->one();
51
        // If it exists, update it rather than having duplicates
52
        if (!empty($testSample)) {
53
            $isNew = false;
54
        }
55
        // Get the validated model attributes and save them to the db
56
        $dataSampleConfig = $dataSample->getAttributes($dataSample->fields());
57
        $db = Craft::$app->getDb();
58
        if ($isNew) {
59
            Craft::debug('Creating new data sample', __METHOD__);
60
            // Create a new record
61
            try {
62
                $db->createCommand()->insert(
63
                    '{{%webperf_data_samples}}',
64
                    $dataSampleConfig
65
                )->execute();
66
            } catch (\Exception $e) {
67
                Craft::error($e->getMessage(), __METHOD__);
68
            }
69
        } else {
70
            Craft::debug('Updating existing data sample', __METHOD__);
71
            // Update the existing record
72
            try {
73
                $db->createCommand()->update(
74
                    '{{%webperf_data_samples}}',
75
                    $dataSampleConfig,
76
                    [
77
                        'requestId' => $dataSample->requestId,
78
                    ]
79
                )->execute();
80
            } catch (\Exception $e) {
81
                Craft::error($e->getMessage(), __METHOD__);
82
            }
83
        }
84
        // Trim orphaned samples
85
        $this->trimOrphanedSamples($dataSample->requestId);
86
        // After adding the DataSample, trim the webperf_data_samples db table
87
        if (Webperf::$settings->automaticallyTrimDataSamples) {
88
            $this->trimDataSamples();
89
        }
90
    }
91
92
    /**
93
     * Trim samples that have the placeholder in the URL, aka they never
94
     * received the Boomerang beacon
95
     *
96
     * @param int $requestId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
97
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
98
    public function trimOrphanedSamples(int $requestId)
99
    {
100
        $db = Craft::$app->getDb();
101
        Craft::debug('Trimming orphaned samples', __METHOD__);
102
        // Update the existing record
103
        try {
104
            $db->createCommand()->delete(
105
                '{{%webperf_data_samples}}',
106
                [
107
                    'and', ['url' => DataSample::PLACEHOLDER_URL],
108
                    ['not', ['requestId' => $requestId]],
109
                ]
110
            )->execute();
111
        } catch (\Exception $e) {
112
            Craft::error($e->getMessage(), __METHOD__);
113
        }
114
    }
115
116
    /**
117
     * Trim the webperf_data_samples db table based on the dataSamplesStoredLimit
118
     * config.php setting
119
     *
120
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
121
     *
122
     * @return int
123
     */
124
    public function trimDataSamples(int $limit = null): int
125
    {
126
        $affectedRows = 0;
127
        $db = Craft::$app->getDb();
128
        $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}');
129
        $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit;
130
131
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
132
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
133
            try {
134
                if ($db->getIsMysql()) {
135
                    // Handle MySQL
136
                    $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...
137
                        "
138
                        DELETE FROM {$quotedTable}
139
                        WHERE id NOT IN (
140
                          SELECT id
141
                          FROM (
142
                            SELECT id
143
                            FROM {$quotedTable}
144
                            ORDER BY dateUpdated DESC
145
                            LIMIT {$limit}
146
                          ) foo
147
                        )
148
                        "
149
                    )->execute();
150
                }
151
                if ($db->getIsPgsql()) {
152
                    // Handle Postgres
153
                    $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...
154
                        "
155
                        DELETE FROM {$quotedTable}
156
                        WHERE id NOT IN (
157
                          SELECT id
158
                          FROM (
159
                            SELECT id
160
                            FROM {$quotedTable}
161
                            ORDER BY \"dateUpdated\" DESC
162
                            LIMIT {$limit}
163
                          ) foo
164
                        )
165
                        "
166
                    )->execute();
167
                }
168
            } catch (\Exception $e) {
169
                Craft::error($e->getMessage(), __METHOD__);
170
            }
171
            Craft::info(
172
                Craft::t(
173
                    'webperf',
174
                    'Trimmed {rows} from webperf_data_samples table',
175
                    ['rows' => $affectedRows]
176
                ),
177
                __METHOD__
178
            );
179
        }
180
181
        return $affectedRows;
182
    }
183
}
184