Passed
Push — v1 ( 01300c...f6b482 )
by Andrew
07:56 queued 04:40
created

ChartsController::actionDashboardSlowestPages()   B

Complexity

Conditions 10
Paths 72

Size

Total Lines 64
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 64
rs 7.6666
c 0
b 0
f 0
cc 10
nc 72
nop 4

How to fix   Long Method    Complexity   

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
                    'url',
150
                    'title',
151
                    'AVG('.$column.') AS avg',
152
                ])
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...
153
                ->where("dateUpdated >= ( CURDATE() - INTERVAL '{$days}' DAY )");
154
            if ((int)$siteId !== 0) {
155
                $query->andWhere(['siteId' => $siteId]);
156
            }
157
            $query
158
                ->orderBy('avg DESC')
159
                ->groupBy('url')
160
                ->limit($limit);
161
            $stats = $query->all();
162
        }
163
        if ($db->getIsPgsql()) {
164
            // Query the db
165
            $query = (new Query())
166
                ->from('{{%webperf_data_samples}}')
167
                ->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...
168
                    'AVG("'.$column.'") AS avg',
169
                ])
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...
170
                ->where("\"dateUpdated\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )");
171
            if ((int)$siteId !== 0) {
172
                $query->andWhere(['siteId' => $siteId]);
173
            }
174
            $stats = $query->all();
175
        }
176
        if ($stats) {
177
            // Decode any emojis in the title
178
            foreach ($stats as &$stat) {
179
                $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
180
            }
181
            $data = $stats;
182
        }
183
184
        return $this->asJson($data);
185
    }
186
187
    /**
188
     * The Dashboard chart
189
     *
190
     * @param int $days
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
191
     *
192
     * @return Response
193
     */
194
    public function actionWidget($days = 1): Response
195
    {
196
        $data = [];
197
        // Different dbs do it different ways
198
        $stats = null;
199
        $handledStats = null;
200
        $db = Craft::$app->getDb();
201
        if ($db->getIsMysql()) {
202
            // Query the db
203
            $stats = (new Query())
204
                ->from('{{%retour_stats}}')
205
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
206
                ->count();
207
            $handledStats = (new Query())
208
                ->from('{{%retour_stats}}')
209
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
210
                ->andWhere('handledByRetour is TRUE')
211
                ->count();
212
        }
213
        if ($db->getIsPgsql()) {
214
            // Query the db
215
            $stats = (new Query())
216
                ->from('{{%retour_stats}}')
217
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
218
                ->count();
219
            $handledStats = (new Query())
220
                ->from('{{%retour_stats}}')
221
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
222
                ->andWhere('"handledByRetour" = TRUE')
223
                ->count();
224
        }
225
        if ($stats) {
226
            $data = [
227
                (int)$stats,
228
                (int)$handledStats,
229
            ];
230
        }
231
232
        return $this->asJson($data);
233
    }
234
235
    // Protected Methods
236
    // =========================================================================
237
}
238