Passed
Push — develop ( 71abba...d7f64b )
by Andrew
09:10
created

DataSamples   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 104
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 49
dl 0
loc 104
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A addDataSample() 0 30 4
A trimDataSamples() 0 58 5
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 nystudio107\webperf\Webperf;
14
use nystudio107\webperf\models\DataSample;
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
19
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
20
 * @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...
21
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
22
 * @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...
23
 */
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...
24
class DataSamples extends Component
25
{
26
    // Public Methods
27
    // =========================================================================
28
29
    public function addDataSample(DataSample $dataSample)
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
30
    {
31
        // Validate the model before saving it to the db
32
        if ($dataSample->validate() === false) {
33
            Craft::error(
34
                Craft::t(
35
                    'webperf',
36
                    'Error validating data sample: {errors}',
37
                    ['errors' => print_r($dataSample->getErrors(), true)]
38
                ),
39
                __METHOD__
40
            );
41
42
            return;
43
        }
44
        // Get the validated model attributes and save them to the db
45
        $dataSampleConfig = $dataSample->getAttributes();
46
        $db = Craft::$app->getDb();
47
        // Create a new record
48
        try {
49
            $db->createCommand()->insert(
50
                '{{%webperf_data_samples}}',
51
                $dataSampleConfig
52
            )->execute();
53
        } catch (\Exception $e) {
54
            Craft::error($e->getMessage(), __METHOD__);
55
        }
56
        // After adding the DataSample, trim the webperf_data_samples db table
57
        if (Webperf::$settings->automaticallyTrimDataSamples) {
58
            $this->trimDataSamples();
59
        }
60
    }
61
62
    /**
63
     * Trim the webperf_data_samples db table based on the dataSamplesStoredLimit
64
     * config.php setting
65
     *
66
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
67
     *
68
     * @return int
69
     */
70
    public function trimDataSamples(int $limit = null): int
71
    {
72
        $affectedRows = 0;
73
        $db = Craft::$app->getDb();
74
        $quotedTable = $db->quoteTableName('{{%webperf_data_samples}}');
75
        $limit = $limit ?? Webperf::$settings->dataSamplesStoredLimit;
76
77
        if ($limit !== null) {
0 ignored issues
show
introduced by
The condition $limit !== null is always true.
Loading history...
78
            //  https://stackoverflow.com/questions/578867/sql-query-delete-all-records-from-the-table-except-latest-n
79
            try {
80
                if ($db->getIsMysql()) {
81
                    // Handle MySQL
82
                    $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...
83
                        "
84
                        DELETE FROM {$quotedTable}
85
                        WHERE id NOT IN (
86
                          SELECT id
87
                          FROM (
88
                            SELECT id
89
                            FROM {$quotedTable}
90
                            ORDER BY hitLastTime DESC
91
                            LIMIT {$limit}
92
                          ) foo
93
                        )
94
                        "
95
                    )->execute();
96
                }
97
                if ($db->getIsPgsql()) {
98
                    // Handle Postgres
99
                    $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...
100
                        "
101
                        DELETE FROM {$quotedTable}
102
                        WHERE id NOT IN (
103
                          SELECT id
104
                          FROM (
105
                            SELECT id
106
                            FROM {$quotedTable}
107
                            ORDER BY \"hitLastTime\" DESC
108
                            LIMIT {$limit}
109
                          ) foo
110
                        )
111
                        "
112
                    )->execute();
113
                }
114
            } catch (\Exception $e) {
115
                Craft::error($e->getMessage(), __METHOD__);
116
            }
117
            Craft::info(
118
                Craft::t(
119
                    'webperf',
120
                    'Trimmed {rows} from webperf_data_samples table',
121
                    ['rows' => $affectedRows]
122
                ),
123
                __METHOD__
124
            );
125
        }
126
127
        return $affectedRows;
128
    }
129
}
130