Passed
Push — v1 ( 62eead...b0cc84 )
by Andrew
07:28 queued 04:24
created

TablesController::actionPagesIndex()   D

Complexity

Conditions 19
Paths 120

Size

Total Lines 124
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 86
dl 0
loc 124
rs 4.35
c 0
b 0
f 0
cc 19
nc 120
nop 5

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 nystudio107\webperf\helpers\Permission as PermissionHelper;
14
15
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...
16
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...
17
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...
18
19
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...
20
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...
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @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...
24
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @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...
26
 */
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...
27
class TablesController extends Controller
28
{
29
    // Constants
30
    // =========================================================================
31
32
    // Protected Properties
33
    // =========================================================================
34
35
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
36
     * @var    bool|array
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 4
Loading history...
37
     */
38
    protected $allowAnonymous = [];
39
40
    // Public Methods
41
    // =========================================================================
42
43
    /**
44
     * Handle requests for the dashboard statistics table
45
     *
46
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
47
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
48
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
49
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     * @param null   $siteId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $siteId is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
51
     *
52
     * @return Response
53
     * @throws ForbiddenHttpException
54
     */
55
    public function actionPagesIndex(
56
        string $sort = 'pageLoad|desc',
57
        int $page = 1,
58
        int $per_page = 20,
59
        $filter = '',
60
        $siteId = 0
61
    ): Response {
62
        PermissionHelper::controllerPermissionCheck('webperf:pages');
63
        $data = [];
64
        $sortField = 'pageLoad';
65
        $sortType = 'DESC';
66
        // Figure out the sorting type
67
        if ($sort !== '') {
68
            if (strpos($sort, '|') === false) {
69
                $sortField = $sort;
70
            } else {
71
                list($sortField, $sortType) = explode('|', $sort);
72
            }
73
        }
74
        if ($sortField === 'totalPageLoad') {
75
            $sortField = 'pageLoad';
76
        }
77
        // Query the db table
78
        $offset = ($page - 1) * $per_page;
79
        $query = (new Query())
80
            ->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...
81
                'url',
82
                'MIN(title) AS title',
83
                'COUNT(url) AS cnt',
84
                'AVG(pageLoad) AS pageLoad',
85
                'AVG(domInteractive) AS domInteractive',
86
                'AVG(firstContentfulPaint) AS firstContentfulPaint',
87
                'AVG(firstPaint) AS firstPaint',
88
                'AVG(firstByte) AS firstByte',
89
                'AVG(connect) AS connect',
90
                'AVG(dns) AS dns',
91
                'AVG(craftTotalMs) AS craftTotalMs',
92
                'AVG(craftDbCnt) AS craftDbCnt',
93
                'AVG(craftDbMs) AS craftDbMs',
94
                'AVG(craftTwigCnt) AS craftTwigCnt',
95
                'AVG(craftTwigMs) AS craftTwigMs',
96
                'AVG(craftTotalMemory) AS craftTotalMemory',
97
            ])
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...
98
            ->from(['{{%webperf_data_samples}}'])
99
            ->offset($offset)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
100
            ;
101
        if ((int)$siteId !== 0) {
102
            $query->where(['siteId' => $siteId]);
103
        }
104
        if ($filter !== '') {
105
            $query
106
                ->where(['like', 'url', $filter])
107
                ->orWhere(['like', 'title', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
108
            ;
109
        }
110
        $query
111
            ->orderBy("{$sortField} {$sortType}")
112
            ->groupBy('url')
113
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
114
        ;
115
116
        $stats = $query->all();
117
        if ($stats) {
118
            // Compute the largest page load time
119
            $maxTotalPageLoad = 0;
120
            foreach ($stats as &$stat) {
121
                // Determine the stat type
122
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
123
                    $stat['type'] = 'both';
124
                }
125
                if (empty($stat['pageLoad'])) {
126
                    $stat['type'] = 'craft';
127
                }
128
                if (empty($stat['craftTotalMs'])) {
129
                    $stat['type'] = 'frontend';
130
                }
131
                if (empty($stat['pageLoad'])) {
132
                    $pageLoad = $stat['craftTotalMs'];
133
                } else {
134
                    $pageLoad = $stat['pageLoad'];
135
                }
136
                if ($pageLoad > $maxTotalPageLoad) {
137
                    $maxTotalPageLoad = $pageLoad;
138
                }
139
            }
140
            // Massage the stats
141
            $index = 1;
142
            foreach ($stats as &$stat) {
143
                $stat['id'] = $index++;
144
                $stat['maxTotalPageLoad'] = (int)$maxTotalPageLoad;
145
                // If there is no frontend beacon timing, use the Craft timing
146
                if (empty($stat['pageLoad'])) {
147
                    $stat['totalPageLoad'] = (int)$stat['craftTotalMs'];
148
                } else {
149
                    $stat['totalPageLoad'] = (int)$stat['pageLoad'];
150
                }
151
                // Decode any emojis in the title
152
                if (!empty($stat['title'])) {
153
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
154
                }
155
            }
156
            // Format the data for the API
157
            $data['data'] = $stats;
158
            $query = (new Query())
159
                ->from(['{{%webperf_data_samples}}'])
160
                ->groupBy('url');
161
            if ($filter !== '') {
162
                $query->where(['like', 'url', $filter]);
163
                $query->orWhere(['like', 'title', $filter]);
164
            }
165
            $count = $query->count();
166
            $data['links']['pagination'] = [
167
                'total' => $count,
168
                'per_page' => $per_page,
169
                'current_page' => $page,
170
                'last_page' => ceil($count / $per_page),
171
                'next_page_url' => null,
172
                'prev_page_url' => null,
173
                'from' => $offset + 1,
174
                'to' => $offset + ($count > $per_page ? $per_page : $count),
175
            ];
176
        }
177
178
        return $this->asJson($data);
179
    }
180
181
    /**
182
     * Handle requests for the dashboard statistics table
183
     *
184
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
185
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
186
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
187
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
188
     * @param string $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
189
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
190
     *
191
     * @return Response
192
     * @throws ForbiddenHttpException
193
     */
194
    public function actionPageDetail(
195
        string $sort = 'pageLoad|desc',
196
        int $page = 1,
197
        int $per_page = 20,
198
        $filter = '',
199
        $pageUrl = '',
200
        $siteId = 0
201
    ): Response {
202
        PermissionHelper::controllerPermissionCheck('webperf:pages');
203
        $data = [];
204
        $sortField = 'pageLoad';
205
        $sortType = 'DESC';
206
        $pageUrl = urldecode($pageUrl);
207
        // Figure out the sorting type
208
        if ($sort !== '') {
209
            if (strpos($sort, '|') === false) {
210
                $sortField = $sort;
211
            } else {
212
                list($sortField, $sortType) = explode('|', $sort);
213
            }
214
        }
215
        if ($sortField === 'totalPageLoad') {
216
            $sortField = 'pageLoad';
217
        }
218
        // Query the db table
219
        $offset = ($page - 1) * $per_page;
220
        $query = (new Query())
221
            ->from(['{{%webperf_data_samples}}'])
222
            ->offset($offset)
223
            ->where(['url' => $pageUrl])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
224
        ;
225
        if ((int)$siteId !== 0) {
226
            $query->where(['siteId' => $siteId]);
227
        }
228
        if ($filter !== '') {
229
            $query
230
                ->andWhere(['like', 'device', $filter])
231
                ->orWhere(['like', 'os', $filter])
232
                ->orWhere(['like', 'browser', $filter])
233
                ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
234
            ;
235
        }
236
        $query
237
            ->orderBy("{$sortField} {$sortType}")
238
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
239
        ;
240
241
        $stats = $query->all();
242
        if ($stats) {
243
            // Compute the largest page load time
244
            $maxTotalPageLoad = 0;
245
            foreach ($stats as &$stat) {
246
                // Determine the stat type
247
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
248
                    $stat['type'] = 'both';
249
                }
250
                if (empty($stat['pageLoad'])) {
251
                    $stat['type'] = 'craft';
252
                }
253
                if (empty($stat['craftTotalMs'])) {
254
                    $stat['type'] = 'frontend';
255
                }
256
                if (empty($stat['pageLoad'])) {
257
                    $pageLoad = $stat['craftTotalMs'];
258
                } else {
259
                    $pageLoad = $stat['pageLoad'];
260
                }
261
                if ($pageLoad > $maxTotalPageLoad) {
262
                    $maxTotalPageLoad = $pageLoad;
263
                }
264
            }
265
            // Massage the stats
266
            $index = 1;
267
            foreach ($stats as &$stat) {
268
                $stat['id'] = $index++;
269
                $stat['maxTotalPageLoad'] = (int)$maxTotalPageLoad;
270
                // If there is no frontend beacon timing, use the Craft timing
271
                if (empty($stat['pageLoad'])) {
272
                    $stat['totalPageLoad'] = (int)$stat['craftTotalMs'];
273
                } else {
274
                    $stat['totalPageLoad'] = (int)$stat['pageLoad'];
275
                }
276
                // Decode any emojis in the title
277
                if (!empty($stat['title'])) {
278
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
279
                }
280
            }
281
            // Format the data for the API
282
            $data['data'] = $stats;
283
            $query = (new Query())
284
                ->from(['{{%webperf_data_samples}}'])
285
                ->where(['url' => $pageUrl])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
286
            ;
287
            if ($filter !== '') {
288
                $query
289
                    ->andWhere(['like', 'device', $filter])
290
                    ->orWhere(['like', 'os', $filter])
291
                    ->orWhere(['like', 'browser', $filter])
292
                    ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
293
                ;
294
            }
295
            $count = $query->count();
296
            $data['links']['pagination'] = [
297
                'total' => $count,
298
                'per_page' => $per_page,
299
                'current_page' => $page,
300
                'last_page' => ceil($count / $per_page),
301
                'next_page_url' => null,
302
                'prev_page_url' => null,
303
                'from' => $offset + 1,
304
                'to' => $offset + ($count > $per_page ? $per_page : $count),
305
            ];
306
        }
307
308
        return $this->asJson($data);
309
    }
310
311
    // Protected Methods
312
    // =========================================================================
313
}
314