Passed
Push — develop ( 0d704e...6a0b9d )
by Andrew
05:15
created

ChartsController::actionDashboardSlowestPages()   B

Complexity

Conditions 9
Paths 72

Size

Total Lines 63
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 63
rs 7.6764
c 0
b 0
f 0
cc 9
nc 72
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\controllers;
12
13
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...
14
use nystudio107\webperf\helpers\Permission as PermissionHelper;
15
16
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...
17
use craft\helpers\ArrayHelper;
0 ignored issues
show
Bug introduced by
The type craft\helpers\ArrayHelper 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\web\Controller;
0 ignored issues
show
Bug introduced by
The type craft\web\Controller 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
use yii\web\ForbiddenHttpException;
0 ignored issues
show
Bug introduced by
The type yii\web\ForbiddenHttpException 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
use yii\web\Response;
0 ignored issues
show
Bug introduced by
The type yii\web\Response 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...
22
23
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
24
 * @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...
25
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
26
 * @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...
27
 */
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...
28
class ChartsController extends Controller
29
{
30
    // Constants
31
    // =========================================================================
32
33
    // Protected Properties
34
    // =========================================================================
35
36
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
37
     * @var    bool|array
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 4
Loading history...
38
     */
39
    protected $allowAnonymous = [
40
    ];
41
42
    // Public Methods
43
    // =========================================================================
44
45
    /**
46
     * The Dashboard stats average chart
47
     *
48
     * @param string $range
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
49
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
51
     *
52
     * @return Response
53
     * @throws ForbiddenHttpException
54
     */
55
    public function actionDashboardStatsAverage(
56
        string $range = 'day',
57
        string $column = 'pageLoad',
58
        int $siteId = 0
59
    ): Response {
60
        PermissionHelper::controllerPermissionCheck('webperf:dashboard');
61
        $data = [];
62
        $days = 1;
63
        switch ($range) {
64
            case 'day':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
65
                $days = 1;
66
                break;
67
            case 'week':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
68
                $days = 7;
69
                break;
70
            case 'month':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
71
                $days = 30;
72
                break;
73
        }
74
        // Different dbs do it different ways
75
        $stats = null;
76
        $db = Craft::$app->getDb();
77
        if ($db->getIsMysql()) {
78
            // Query the db
79
            $query = (new Query())
80
                ->from('{{%webperf_data_samples}}')
81
                ->select([
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...
82
                    'AVG('.$column.') AS avg',
83
                ])
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...
84
                ->where("dateUpdated >= ( CURDATE() - INTERVAL '{$days}' DAY )");
85
            if ((int)$siteId !== 0) {
86
                $query->andWhere(['siteId' => $siteId]);
87
            }
88
            $stats = $query->all();
89
        }
90
        if ($db->getIsPgsql()) {
91
            // Query the db
92
            $query = (new Query())
93
                ->from('{{%webperf_data_samples}}')
94
                ->select([
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...
95
                    'AVG("'.$column.'") AS avg',
96
                ])
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...
97
                ->where("\"dateUpdated\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )");
98
            if ((int)$siteId !== 0) {
99
                $query->andWhere(['siteId' => $siteId]);
100
            }
101
            $stats = $query->all();
102
        }
103
        if ($stats) {
104
            $data = ArrayHelper::getColumn($stats, 'avg');
105
        }
106
107
        return $this->asJson($data);
108
    }
109
110
    /**
111
     * The Dashboard stats slowest pages list
112
     *
113
     * @param string $range
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
114
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
115
     * @param int    $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
116
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
117
     *
118
     * @return Response
119
     * @throws ForbiddenHttpException
120
     */
121
    public function actionDashboardSlowestPages(
122
        string $range = 'day',
123
        string $column = 'pageLoad',
124
        int $limit = 3,
125
        int $siteId = 0
126
    ): Response {
127
        PermissionHelper::controllerPermissionCheck('webperf:dashboard');
128
        $data = [];
129
        $days = 1;
130
        switch ($range) {
131
            case 'day':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
132
                $days = 1;
133
                break;
134
            case 'week':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
135
                $days = 7;
136
                break;
137
            case 'month':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
138
                $days = 30;
139
                break;
140
        }
141
        // Different dbs do it different ways
142
        $stats = null;
143
        $db = Craft::$app->getDb();
144
        if ($db->getIsMysql()) {
145
            // Query the db
146
            $query = (new Query())
147
                ->from('{{%webperf_data_samples}}')
148
                ->select([
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...
149
                    '*',
150
                    'AVG('.$column.') AS avg',
151
                ])
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...
152
                ->where("dateUpdated >= ( CURDATE() - INTERVAL '{$days}' DAY )");
153
            if ((int)$siteId !== 0) {
154
                $query->andWhere(['siteId' => $siteId]);
155
            }
156
            $query
157
                ->orderBy('avg DESC')
158
                ->groupBy('url')
159
                ->limit($limit);
160
            $stats = $query->all();
161
        }
162
        if ($db->getIsPgsql()) {
163
            // Query the db
164
            $query = (new Query())
165
                ->from('{{%webperf_data_samples}}')
166
                ->select([
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...
167
                    'AVG("'.$column.'") AS avg',
168
                ])
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...
169
                ->where("\"dateUpdated\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )");
170
            if ((int)$siteId !== 0) {
171
                $query->andWhere(['siteId' => $siteId]);
172
            }
173
            $stats = $query->all();
174
        }
175
        if ($stats) {
176
            $data = ArrayHelper::getColumn($stats, 'avg');
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
177
        }
178
179
        Craft::debug('Slowest Pages: '.print_r($stats, true), __METHOD__);
180
181
        $data = [];
182
183
        return $this->asJson($data);
184
    }
185
186
    /**
187
     * The Dashboard chart
188
     *
189
     * @param int $days
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
190
     *
191
     * @return Response
192
     */
193
    public function actionWidget($days = 1): Response
194
    {
195
        $data = [];
196
        // Different dbs do it different ways
197
        $stats = null;
198
        $handledStats = null;
199
        $db = Craft::$app->getDb();
200
        if ($db->getIsMysql()) {
201
            // Query the db
202
            $stats = (new Query())
203
                ->from('{{%retour_stats}}')
204
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
205
                ->count();
206
            $handledStats = (new Query())
207
                ->from('{{%retour_stats}}')
208
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
209
                ->andWhere('handledByRetour is TRUE')
210
                ->count();
211
        }
212
        if ($db->getIsPgsql()) {
213
            // Query the db
214
            $stats = (new Query())
215
                ->from('{{%retour_stats}}')
216
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
217
                ->count();
218
            $handledStats = (new Query())
219
                ->from('{{%retour_stats}}')
220
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
221
                ->andWhere('"handledByRetour" = TRUE')
222
                ->count();
223
        }
224
        if ($stats) {
225
            $data = [
226
                (int)$stats,
227
                (int)$handledStats,
228
            ];
229
        }
230
231
        return $this->asJson($data);
232
    }
233
234
    // Protected Methods
235
    // =========================================================================
236
}
237