Passed
Push — v1 ( 1d50f7...7c9bec )
by Andrew
06:09 queued 03:01
created

TablesController::actionPagesIndex()   D

Complexity

Conditions 18
Paths 60

Size

Total Lines 137
Code Lines 93

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 93
dl 0
loc 137
rs 4.046
c 0
b 0
f 0
cc 18
nc 60
nop 7

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) 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\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...
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 TablesController 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
    // Public Methods
42
    // =========================================================================
43
44
    /**
45
     * Handle requests for the dashboard statistics table
46
     *
47
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $sort does not match actual variable name $start
Loading history...
48
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $page does not match actual variable name $end
Loading history...
49
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $per_page does not match actual variable name $sort
Loading history...
50
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $filter does not match actual variable name $page
Loading history...
51
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $start does not match actual variable name $per_page
Loading history...
52
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $end does not match actual variable name $filter
Loading history...
53
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
54
     *
55
     * @return Response
56
     * @throws ForbiddenHttpException
57
     */
58
    public function actionPagesIndex(
59
        string $start = '',
60
        string $end = '',
61
        string $sort = 'totalPageLoad|desc',
62
        int $page = 1,
63
        int $per_page = 20,
64
        $filter = '',
65
        $siteId = 0
66
    ): Response {
67
        PermissionHelper::controllerPermissionCheck('webperf:pages');
68
        $data = [];
69
        $sortField = 'totalPageLoad';
70
        $sortType = 'DESC';
71
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
72
        $end = date('Y-m-d', strtotime($end.'+1 day'));
73
        // Figure out the sorting type
74
        if ($sort !== '') {
75
            if (strpos($sort, '|') === false) {
76
                $sortField = $sort;
77
            } else {
78
                list($sortField, $sortType) = explode('|', $sort);
79
            }
80
        }
81
        // Query the db table
82
        $offset = ($page - 1) * $per_page;
83
        $query = (new Query())
84
            ->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...
85
                'url',
86
                'MIN(title) AS title',
87
                'COUNT(url) AS cnt',
88
                'GREATEST(AVG(pageLoad), AVG(craftTotalMs)) AS totalPageLoad',
89
                'AVG(pageLoad) AS pageLoad',
90
                'AVG(domInteractive) AS domInteractive',
91
                'AVG(firstContentfulPaint) AS firstContentfulPaint',
92
                'AVG(firstPaint) AS firstPaint',
93
                'AVG(firstByte) AS firstByte',
94
                'AVG(connect) AS connect',
95
                'AVG(dns) AS dns',
96
                'AVG(craftTotalMs) AS craftTotalMs',
97
                'AVG(craftDbCnt) AS craftDbCnt',
98
                'AVG(craftDbMs) AS craftDbMs',
99
                'AVG(craftTwigCnt) AS craftTwigCnt',
100
                'AVG(craftTwigMs) AS craftTwigMs',
101
                'AVG(craftTotalMemory) AS craftTotalMemory',
102
            ])
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...
103
            ->from(['{{%webperf_data_samples}}'])
104
            ->offset($offset)
105
            ->where(['between', 'dateUpdated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
106
        ;
107
        if ((int)$siteId !== 0) {
108
            $query->andWhere(['siteId' => $siteId]);
109
        }
110
        if ($filter !== '') {
111
            $query
112
                ->andWhere(['like', 'url', $filter])
113
                ->orWhere(['like', 'title', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
114
            ;
115
        }
116
        $query
117
            ->orderBy("{$sortField} {$sortType}")
118
            ->groupBy('url')
119
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
120
        ;
121
122
        $stats = $query->all();
123
        if ($stats) {
124
            // Compute the largest page load time
125
            $maxTotalPageLoad = 0;
126
            foreach ($stats as &$stat) {
127
                // Determine the stat type
128
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
129
                    $stat['type'] = 'both';
130
                }
131
                if (empty($stat['pageLoad'])) {
132
                    $stat['type'] = 'craft';
133
                }
134
                if (empty($stat['craftTotalMs'])) {
135
                    $stat['type'] = 'frontend';
136
                }
137
                if ($stat['totalPageLoad'] > $maxTotalPageLoad) {
138
                    $maxTotalPageLoad = $stat['totalPageLoad'];
139
                }
140
            }
141
            // Massage the stats
142
            $index = 1;
143
            foreach ($stats as &$stat) {
144
                $stat['id'] = $index++;
145
                $stat['cnt'] = (int)$stat['cnt'];
146
                $stat['totalPageLoad'] = (int)$stat['totalPageLoad'];
147
                $stat['maxTotalPageLoad'] = (int)$maxTotalPageLoad;
148
                // Decode any emojis in the title
149
                if (!empty($stat['title'])) {
150
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
151
                }
152
                // Set up the appropriate helper links
153
                $stat['deleteLink'] = UrlHelper::actionUrl('webperf/data-samples/delete-samples-by-url', [
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...
154
                    'pageUrl' => $stat['url'],
155
                    'siteId' => $siteId
156
                ]);
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...
157
                $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...
158
                    'pageUrl' => $stat['url'],
159
                    'siteId' => $siteId,
160
                ]);
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...
161
                // Override based on permissions
162
                $user = Craft::$app->getUser()->getIdentity();
163
                if (!$user->can('webperf:delete-data-samples')) {
164
                    $stat['deleteLink'] = '';
165
                }
166
                if (!$user->can('webperf:page-detail')) {
167
                    $stat['detailPageUrl'] = '';
168
                }
169
            }
170
            // Format the data for the API
171
            $data['data'] = $stats;
172
            $query = (new Query())
173
                ->from(['{{%webperf_data_samples}}'])
174
                ->groupBy('url')
175
                ->where(['between', 'dateUpdated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
176
                ;
177
            if ($filter !== '') {
178
                $query->andWhere(['like', 'url', $filter]);
179
                $query->orWhere(['like', 'title', $filter]);
180
            }
181
            $count = $query->count();
182
            $data['links']['pagination'] = [
183
                'total' => $count,
184
                'per_page' => $per_page,
185
                'current_page' => $page,
186
                'last_page' => ceil($count / $per_page),
187
                'next_page_url' => null,
188
                'prev_page_url' => null,
189
                'from' => $offset + 1,
190
                'to' => $offset + ($count > $per_page ? $per_page : $count),
191
            ];
192
        }
193
194
        return $this->asJson($data);
195
    }
196
197
    /**
198
     * Handle requests for the dashboard statistics table
199
     *
200
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $sort does not match actual variable name $start
Loading history...
201
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $page does not match actual variable name $end
Loading history...
202
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $per_page does not match actual variable name $sort
Loading history...
203
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $filter does not match actual variable name $page
Loading history...
204
     * @param string $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $pageUrl does not match actual variable name $per_page
Loading history...
205
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $start does not match actual variable name $filter
Loading history...
206
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $end does not match actual variable name $pageUrl
Loading history...
207
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
208
     *
209
     * @return Response
210
     * @throws ForbiddenHttpException
211
     */
212
    public function actionPageDetail(
213
        string $start = '',
214
        string $end = '',
215
        string $sort = 'totalPageLoad|desc',
216
        int $page = 1,
217
        int $per_page = 20,
218
        $filter = '',
219
        $pageUrl = '',
220
        $siteId = 0
221
    ): Response {
222
        PermissionHelper::controllerPermissionCheck('webperf:pages');
223
        $data = [];
224
        $sortField = 'totalPageLoad';
225
        $sortType = 'DESC';
226
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
227
        $end = date('Y-m-d', strtotime($end.'+1 day'));
228
        $pageUrl = urldecode($pageUrl);
229
        // Figure out the sorting type
230
        if ($sort !== '') {
231
            if (strpos($sort, '|') === false) {
232
                $sortField = $sort;
233
            } else {
234
                list($sortField, $sortType) = explode('|', $sort);
235
            }
236
        }
237
        // Query the db table
238
        $offset = ($page - 1) * $per_page;
239
        $query = (new Query())
240
            ->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...
241
                '*',
242
                'GREATEST(AVG(pageLoad), AVG(craftTotalMs)) AS totalPageLoad',
243
            ])
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...
244
            ->from(['{{%webperf_data_samples}}'])
245
            ->offset($offset)
246
            ->where(['url' => $pageUrl])
247
            ->andWhere(['between', 'dateUpdated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
248
        ;
249
        if ((int)$siteId !== 0) {
250
            $query->andWhere(['siteId' => $siteId]);
251
        }
252
        if ($filter !== '') {
253
            $query
254
                ->andWhere(['like', 'device', $filter])
255
                ->orWhere(['like', 'os', $filter])
256
                ->orWhere(['like', 'browser', $filter])
257
                ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
258
            ;
259
        }
260
        $query
261
            ->orderBy("{$sortField} {$sortType}")
262
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
263
        ;
264
265
        $stats = $query->all();
266
        if ($stats) {
267
            // Compute the largest page load time
268
            $maxTotalPageLoad = 0;
269
            foreach ($stats as &$stat) {
270
                // Determine the stat type
271
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
272
                    $stat['type'] = 'both';
273
                }
274
                if (empty($stat['pageLoad'])) {
275
                    $stat['type'] = 'craft';
276
                }
277
                if (empty($stat['craftTotalMs'])) {
278
                    $stat['type'] = 'frontend';
279
                }
280
                if ($stat['totalPageLoad'] > $maxTotalPageLoad) {
281
                    $maxTotalPageLoad = (int)$stat['totalPageLoad'];
282
                }
283
            }
284
            // Massage the stats
285
            foreach ($stats as &$stat) {
286
                $stat['totalPageLoad'] = (int)$stat['totalPageLoad'];
287
                $stat['maxTotalPageLoad'] = (int)$maxTotalPageLoad;
288
                // Decode any emojis in the title
289
                if (!empty($stat['title'])) {
290
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
291
                }
292
                $stat['deleteLink'] = UrlHelper::actionUrl('webperf/data-samples/delete-sample-by-id', [
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...
293
                    'id' => $stat['id']
294
                ]);
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...
295
                // Override based on permissions
296
                $user = Craft::$app->getUser()->getIdentity();
297
                if (!$user->can('webperf:delete-data-samples')) {
298
                    $stat['deleteLink'] = '';
299
                }
300
            }
301
            // Format the data for the API
302
            $data['data'] = $stats;
303
            $query = (new Query())
304
                ->from(['{{%webperf_data_samples}}'])
305
                ->where(['url' => $pageUrl])
306
                ->andWhere(['between', 'dateUpdated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
307
            ;
308
            if ($filter !== '') {
309
                $query
310
                    ->andWhere(['like', 'device', $filter])
311
                    ->orWhere(['like', 'os', $filter])
312
                    ->orWhere(['like', 'browser', $filter])
313
                    ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
314
                ;
315
            }
316
            $count = $query->count();
317
            $data['links']['pagination'] = [
318
                'total' => $count,
319
                'per_page' => $per_page,
320
                'current_page' => $page,
321
                'last_page' => ceil($count / $per_page),
322
                'next_page_url' => null,
323
                'prev_page_url' => null,
324
                'from' => $offset + 1,
325
                'to' => $offset + ($count > $per_page ? $per_page : $count),
326
            ];
327
        }
328
329
        return $this->asJson($data);
330
    }
331
332
    // Protected Methods
333
    // =========================================================================
334
}
335