Passed
Push — v1 ( 06dc74...d9854b )
by Andrew
06:57 queued 03:49
created

TablesController::actionPagesIndex()   D

Complexity

Conditions 18
Paths 60

Size

Total Lines 135
Code Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 91
dl 0
loc 135
rs 4.0896
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\DateTimeHelper;
0 ignored issues
show
Bug introduced by
The type craft\helpers\DateTimeHelper 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 TablesController 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
     * Handle requests for the dashboard statistics table
47
     *
48
     * @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...
49
     * @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...
50
     * @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...
51
     * @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...
52
     * @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...
53
     * @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...
54
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
55
     *
56
     * @return Response
57
     * @throws ForbiddenHttpException
58
     */
59
    public function actionPagesIndex(
60
        string $start = '',
61
        string $end = '',
62
        string $sort = 'pageLoad|DESC',
63
        int $page = 1,
64
        int $per_page = 20,
65
        $filter = '',
66
        $siteId = 0
67
    ): Response {
68
        PermissionHelper::controllerPermissionCheck('webperf:pages');
69
        $data = [];
70
        $sortField = 'pageLoad';
71
        $sortType = 'DESC';
72
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
73
        $end = date('Y-m-d', strtotime($end.'+1 day'));
74
        // Figure out the sorting type
75
        if ($sort !== '') {
76
            if (strpos($sort, '|') === false) {
77
                $sortField = $sort;
78
            } else {
79
                list($sortField, $sortType) = explode('|', $sort);
80
            }
81
        }
82
        // Query the db table
83
        $offset = ($page - 1) * $per_page;
84
        $query = (new Query())
85
            ->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...
86
                'url',
87
                'MIN(title) AS title',
88
                'COUNT(url) AS cnt',
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', 'dateCreated', $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
            $user = Craft::$app->getUser()->getIdentity();
125
            // Compute the largest page load time
126
            $maxTotalPageLoad = 0;
127
            foreach ($stats as &$stat) {
128
             // Determine the stat type
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 16 spaces, found 13
Loading history...
129
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
130
                    $stat['type'] = 'both';
131
                }
132
                if (empty($stat['firstByte'])) {
133
                    $stat['type'] = 'craft';
134
                }
135
                if (empty($stat['craftTotalMs'])) {
136
                    $stat['type'] = 'frontend';
137
                }
138
                if ($stat['pageLoad'] > $maxTotalPageLoad) {
139
                    $maxTotalPageLoad = $stat['pageLoad'];
140
                }
141
            }
142
            // Massage the stats
143
            $index = 1;
144
            foreach ($stats as &$stat) {
145
                $stat['id'] = $index++;
146
                $stat['cnt'] = (int)$stat['cnt'];
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
                if (!$user->can('webperf:delete-data-samples')) {
163
                    $stat['deleteLink'] = '';
164
                }
165
                if (!$user->can('webperf:page-detail')) {
166
                    $stat['detailPageUrl'] = '';
167
                }
168
            }
169
            // Format the data for the API
170
            $data['data'] = $stats;
171
            $query = (new Query())
172
                ->from(['{{%webperf_data_samples}}'])
173
                ->groupBy('url')
174
                ->where(['between', 'dateCreated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
175
                ;
176
            if ($filter !== '') {
177
                $query->andWhere(['like', 'url', $filter]);
178
                $query->orWhere(['like', 'title', $filter]);
179
            }
180
            $count = $query->count();
181
            $data['links']['pagination'] = [
182
                'total' => $count,
183
                'per_page' => $per_page,
184
                'current_page' => $page,
185
                'last_page' => ceil($count / $per_page),
186
                'next_page_url' => null,
187
                'prev_page_url' => null,
188
                'from' => $offset + 1,
189
                'to' => $offset + ($count > $per_page ? $per_page : $count),
190
            ];
191
        }
192
193
        return $this->asJson($data);
194
    }
195
196
    /**
197
     * Handle requests for the dashboard statistics table
198
     *
199
     * @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...
200
     * @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...
201
     * @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...
202
     * @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...
203
     * @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...
204
     * @param string $start
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $start does not match actual variable name $filter
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
205
     * @param string $end
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $end does not match actual variable name $pageUrl
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
206
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
207
     *
208
     * @return Response
209
     * @throws ForbiddenHttpException
210
     */
211
    public function actionPageDetail(
212
        string $start = '',
213
        string $end = '',
214
        string $sort = 'pageLoad|DESC',
215
        int $page = 1,
216
        int $per_page = 20,
217
        $filter = '',
218
        $pageUrl = '',
219
        $siteId = 0
220
    ): Response {
221
        PermissionHelper::controllerPermissionCheck('webperf:pages');
222
        $data = [];
223
        $sortField = 'pageLoad';
224
        $sortType = 'DESC';
225
        // Add a day since YYYY-MM-DD is really YYYY-MM-DD 00:00:00
226
        $end = date('Y-m-d', strtotime($end.'+1 day'));
227
        $pageUrl = urldecode($pageUrl);
228
        // Figure out the sorting type
229
        if ($sort !== '') {
230
            if (strpos($sort, '|') === false) {
231
                $sortField = $sort;
232
            } else {
233
                list($sortField, $sortType) = explode('|', $sort);
234
            }
235
        }
236
        // Query the db table
237
        $offset = ($page - 1) * $per_page;
238
        $query = (new Query())
239
            ->from(['{{%webperf_data_samples}}'])
240
            ->offset($offset)
241
            ->where(['url' => $pageUrl])
242
            ->andWhere(['between', 'dateCreated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
243
        ;
244
        if ((int)$siteId !== 0) {
245
            $query->andWhere(['siteId' => $siteId]);
246
        }
247
        if ($filter !== '') {
248
            $query
249
                ->andWhere(['like', 'device', $filter])
250
                ->orWhere(['like', 'os', $filter])
251
                ->orWhere(['like', 'browser', $filter])
252
                ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
253
            ;
254
        }
255
        $query
256
            ->orderBy("{$sortField} {$sortType}")
257
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
258
        ;
259
        $stats = $query->all();
260
        if ($stats) {
261
            $user = Craft::$app->getUser()->getIdentity();
262
            // Compute the largest page load time
263
            $maxTotalPageLoad = 0;
264
            foreach ($stats as &$stat) {
265
                // Determine the stat type
266
                if (!empty($stat['pageLoad']) && !empty($stat['craftTotalMs'])) {
267
                    $stat['type'] = 'both';
268
                }
269
                if (empty($stat['firstByte'])) {
270
                    $stat['type'] = 'craft';
271
                }
272
                if (empty($stat['craftTotalMs'])) {
273
                    $stat['type'] = 'frontend';
274
                }
275
                if ($stat['pageLoad'] > $maxTotalPageLoad) {
276
                    $maxTotalPageLoad = (int)$stat['pageLoad'];
277
                }
278
            }
279
            // Massage the stats
280
            foreach ($stats as &$stat) {
281
                if (!empty($stats['dateCreated'])) {
282
                    $date = DateTimeHelper::toDateTime($stats['dateCreated']);
283
                    $stats['dateCreated'] = $date->format('Y-m-d H:i:s');
284
                }
285
                $stat['mobile'] = (bool)$stat['mobile'];
286
                $stat['maxTotalPageLoad'] = (int)$maxTotalPageLoad;
287
                // Decode any emojis in the title
288
                if (!empty($stat['title'])) {
289
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
290
                }
291
                $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...
292
                    'id' => $stat['id']
293
                ]);
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...
294
                // Override based on permissions
295
                if (!$user->can('webperf:delete-data-samples')) {
296
                    $stat['deleteLink'] = '';
297
                }
298
            }
299
            // Format the data for the API
300
            $data['data'] = $stats;
301
            $query = (new Query())
302
                ->from(['{{%webperf_data_samples}}'])
303
                ->where(['url' => $pageUrl])
304
                ->andWhere(['between', 'dateCreated', $start, $end])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
305
            ;
306
            if ($filter !== '') {
307
                $query
308
                    ->andWhere(['like', 'device', $filter])
309
                    ->orWhere(['like', 'os', $filter])
310
                    ->orWhere(['like', 'browser', $filter])
311
                    ->orWhere(['like', 'countryCode', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
312
                ;
313
            }
314
            $count = $query->count();
315
            $data['links']['pagination'] = [
316
                'total' => $count,
317
                'per_page' => $per_page,
318
                'current_page' => $page,
319
                'last_page' => ceil($count / $per_page),
320
                'next_page_url' => null,
321
                'prev_page_url' => null,
322
                'from' => $offset + 1,
323
                'to' => $offset + ($count > $per_page ? $per_page : $count),
324
            ];
325
        }
326
327
        return $this->asJson($data);
328
    }
329
330
    // Protected Methods
331
    // =========================================================================
332
}
333