Passed
Push — v1 ( a04106...17dfe3 )
by Andrew
06:07 queued 02:58
created

ChartsController::actionPagesAreaChart()   B

Complexity

Conditions 7
Paths 40

Size

Total Lines 107
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 78
dl 0
loc 107
rs 7.5466
c 0
b 0
f 0
cc 7
nc 40
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) 2019 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 nystudio107\webperf\helpers\Permission as PermissionHelper;
14
15
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...
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\helpers\UrlHelper;
0 ignored issues
show
Bug introduced by
The type craft\helpers\UrlHelper 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
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...
20
21
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...
22
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...
23
24
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
25
 * @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...
26
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
27
 * @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...
28
 */
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...
29
class ChartsController extends Controller
30
{
31
    // Constants
32
    // =========================================================================
33
34
    // Protected Properties
35
    // =========================================================================
36
37
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
38
     * @var    bool|array
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 4
Loading history...
39
     */
40
    protected $allowAnonymous = [];
41
42
    // Public Methods
43
    // =========================================================================
44
45
    /**
46
     * The Dashboard stats average chart
47
     *
48
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
49
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
51
     * @param string $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
52
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
53
     *
54
     * @return Response
55
     * @throws ForbiddenHttpException
56
     */
57
    public function actionDashboardStatsAverage(
58
        string $start,
59
        string $end,
60
        string $column = 'pageLoad',
61
        $pageUrl = '',
62
        int $siteId = 0
63
    ): Response {
64
        PermissionHelper::controllerPermissionCheck('webperf:dashboard');
65
        $data = [];
66
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
67
        $end = date('Y-m-d', strtotime($end.'+1 day'));
68
        $pageUrl = urldecode($pageUrl);
69
        // Different dbs do it different ways
70
        $stats = null;
71
        $db = Craft::$app->getDb();
72
        if ($db->getIsMysql()) {
73
            // Query the db
74
            $query = (new Query())
75
                ->from('{{%webperf_data_samples}}')
76
                ->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...
77
                    'COUNT(url) AS cnt',
78
                    'AVG('.$column.') AS avg',
79
                ])
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...
80
                ->where(['between', 'dateUpdated', $start, $end])
81
                ->andWhere(['not', [$column => null]]);
82
            if ((int)$siteId !== 0) {
83
                $query->andWhere(['siteId' => $siteId]);
84
            }
85
            if ($pageUrl !== '') {
86
                $query->andWhere(['url' => $pageUrl]);
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(['between', 'dateUpdated', $start, $end])
98
                ->andWhere(['not', [$column => null]]);
99
            if ((int)$siteId !== 0) {
100
                $query->andWhere(['siteId' => $siteId]);
101
            }
102
            $stats = $query->all();
103
        }
104
        // Massage the data
105
        if ($stats) {
106
            foreach ($stats as &$stat) {
107
                $stat['cnt'] = (int)$stat['cnt'];
108
            }
109
            $data = $stats[0];
110
        }
111
112
        return $this->asJson($data);
113
    }
114
115
    /**
116
     * The Dashboard stats slowest pages list
117
     *
118
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
119
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
120
     * @param string $column
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
121
     * @param int    $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
122
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
123
     *
124
     * @return Response
125
     * @throws ForbiddenHttpException
126
     */
127
    public function actionDashboardSlowestPages(
128
        string $start,
129
        string $end,
130
        string $column = 'pageLoad',
131
        int $limit = 3,
132
        int $siteId = 0
133
    ): Response {
134
        PermissionHelper::controllerPermissionCheck('webperf:dashboard');
135
        $data = [];
136
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
137
        $end = date('Y-m-d', strtotime($end.'+1 day'));
138
        // Different dbs do it different ways
139
        $stats = null;
140
        $db = Craft::$app->getDb();
141
        if ($db->getIsMysql()) {
142
            // Query the db
143
            $query = (new Query())
144
                ->from('{{%webperf_data_samples}}')
145
                ->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...
146
                    'url',
147
                    'MIN(title) AS title',
148
                    'COUNT(url) AS cnt',
149
                    'AVG('.$column.') AS avg',
150
                ])
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...
151
                ->where(['between', 'dateUpdated', $start, $end])
152
                ->andWhere(['not', [$column => null]]);
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
                    'url',
168
                    'MIN("title") AS title',
169
                    'COUNT(url) AS cnt',
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(['between', 'dateUpdated', $start, $end])
173
                ->andWhere(['not', [$column => null]]);
174
            if ((int)$siteId !== 0) {
175
                $query->andWhere(['siteId' => $siteId]);
176
            }
177
            $query
178
                ->orderBy('avg DESC')
179
                ->groupBy('url')
180
                ->limit($limit);
181
            $stats = $query->all();
182
        }
183
        // Massage the data
184
        if ($stats) {
185
            foreach ($stats as &$stat) {
186
                $stat['cnt'] = (int)$stat['cnt'];
187
                $stat['detailPageUrl'] = UrlHelper::cpUrl('webperf/page-detail', [
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...
188
                    'pageUrl' => $stat['url'],
189
                    'siteId' => $siteId,
190
                ]);
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...
191
                // Decode any emojis in the title
192
                if (!empty($stat['title'])) {
193
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
194
                }
195
            }
196
            $data = $stats;
197
        }
198
199
        return $this->asJson($data);
200
    }
201
202
    /**
203
     * The Dashboard stats average chart
204
     *
205
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
206
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
207
     * @param string $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
208
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
209
     *
210
     * @return Response
211
     * @throws ForbiddenHttpException
212
     */
213
    public function actionPagesAreaChart(
214
        string $start,
215
        string $end,
216
        $pageUrl = '',
217
        int $siteId = 0
218
    ): Response {
219
        PermissionHelper::controllerPermissionCheck('webperf:dashboard');
220
        $data = [];
221
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
222
        $end = date('Y-m-d', strtotime($end.'+1 day'));
223
        $pageUrl = urldecode($pageUrl);
224
        $dateStart = new \DateTime($start);
225
        $dateEnd = new \DateTime($end);
226
        $interval = date_diff($dateStart, $dateEnd);
227
        $dateFormat = '"%Y-%m-%d %l%p"';
228
        if ($interval->days > 30) {
229
            $dateFormat = '"%Y-%m-%d"';
230
        }
231
        // Different dbs do it different ways
232
        $stats = null;
233
        $db = Craft::$app->getDb();
234
        if ($db->getIsMysql()) {
235
            // Query the db
236
            $query = (new Query())
237
                ->from('{{%webperf_data_samples}}')
238
                ->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...
239
                    'AVG(pageLoad) AS pageLoad',
240
                    'AVG(domInteractive) AS domInteractive',
241
                    'AVG(firstContentfulPaint) AS firstContentfulPaint',
242
                    'AVG(firstPaint) AS firstPaint',
243
                    'AVG(firstByte) AS firstByte',
244
                    'AVG(connect) AS connect',
245
                    'AVG(dns) AS dns',
246
                    'AVG(craftTotalMs) AS craftTotalMs',
247
                    'AVG(craftTwigMs) AS craftTwigMs',
248
                    'AVG(craftDbMs) AS craftDbMs',
249
                    'DATE_FORMAT(dateUpdated, '.$dateFormat.') AS sampleDate',
250
                ])
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...
251
                ->where(['between', 'dateUpdated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
252
                ;
253
            if ((int)$siteId !== 0) {
254
                $query->andWhere(['siteId' => $siteId]);
255
            }
256
            if ($pageUrl !== '') {
257
                $query->andWhere(['url' => $pageUrl]);
258
            }
259
            $stats = $query
260
                ->groupBy('sampleDate')
261
                ->all();
262
        }
263
        if ($db->getIsPgsql()) {
264
        }
265
        // Massage the data
266
        if ($stats) {
267
            $data[] = [
268
                'name' => 'Database Queries',
269
                'data' => ArrayHelper::getColumn($stats, 'craftDbMs'),
270
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
271
            ];
272
            $data[] = [
273
                'name' => 'Twig Rendering',
274
                'data' => ArrayHelper::getColumn($stats, 'craftTwigMs'),
275
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
276
            ];
277
            $data[] = [
278
                'name' => 'Craft Rendering',
279
                'data' => ArrayHelper::getColumn($stats, 'craftTotalMs'),
280
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
281
            ];
282
            $data[] = [
283
                'name' => 'DNS Lookup',
284
                'data' => ArrayHelper::getColumn($stats, 'dns'),
285
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
286
            ];
287
            $data[] = [
288
                'name' => 'Connect',
289
                'data' => ArrayHelper::getColumn($stats, 'connect'),
290
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
291
            ];
292
            $data[] = [
293
                'name' => 'First Byte',
294
                'data' => ArrayHelper::getColumn($stats, 'firstByte'),
295
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
296
            ];
297
            $data[] = [
298
                'name' => 'First Paint',
299
                'data' => ArrayHelper::getColumn($stats, 'firstPaint'),
300
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
301
            ];
302
            $data[] = [
303
                'name' => 'First Contentful Paint',
304
                'data' => ArrayHelper::getColumn($stats, 'firstContentfulPaint'),
305
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
306
            ];
307
            $data[] = [
308
                'name' => 'DOM Interactive',
309
                'data' => ArrayHelper::getColumn($stats, 'domInteractive'),
310
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
311
            ];
312
            $data[] = [
313
                'name' => 'Page Load',
314
                'data' => ArrayHelper::getColumn($stats, 'pageLoad'),
315
                'labels' => ArrayHelper::getColumn($stats, 'sampleDate'),
316
            ];
317
        }
318
319
        return $this->asJson($data);
320
    }
321
322
    /**
323
     * The Dashboard chart
324
     *
325
     * @param int $days
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
326
     *
327
     * @return Response
328
     */
329
    public function actionWidget($days = 1): Response
330
    {
331
        $data = [];
332
        return $this->asJson($data);
333
    }
334
335
    // Protected Methods
336
    // =========================================================================
337
}
338