Passed
Push — v1 ( 9b126e...65d641 )
by Andrew
07:00 queued 03:20
created

ChartsController::actionDashboardSlowestPages()   C

Complexity

Conditions 11
Paths 72

Size

Total Lines 72
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

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