Passed
Push — v1 ( f3f274...fd0661 )
by Andrew
12:23 queued 06:47
created

TablesController::actionPagesIndex()   C

Complexity

Conditions 15
Paths 120

Size

Total Lines 116
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 80
dl 0
loc 116
rs 5.0363
c 0
b 0
f 0
cc 15
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
86
                'AVG(domInteractive) AS domInteractive',
87
                'AVG(firstContentfulPaint) AS firstContentfulPaint',
88
                'AVG(firstPaint) AS firstPaint',
89
                'AVG(firstByte) AS firstByte',
90
                'AVG(connect) AS connect',
91
                'AVG(dns) AS dns',
92
93
                'AVG(craftTotalMs) AS craftTotalMs',
94
                'AVG(craftDbCnt) AS craftDbCnt',
95
                'AVG(craftDbMs) AS craftDbMs',
96
                'AVG(craftTwigCnt) AS craftTwigCnt',
97
                'AVG(craftTwigMs) AS craftTwigMs',
98
                'AVG(craftTotalMemory) AS craftTotalMemory',
99
            ])
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...
100
            ->from(['{{%webperf_data_samples}}'])
101
            ->offset($offset)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
102
            ;
103
        if ((int)$siteId !== 0) {
104
            $query->where(['siteId' => $siteId]);
105
        }
106
        if ($filter !== '') {
107
            $query
108
                ->where(['like', 'url', $filter])
109
                ->orWhere(['like', 'title', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
110
            ;
111
        }
112
        $query
113
            ->orderBy("{$sortField} {$sortType}")
114
            ->groupBy('url')
115
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
116
        ;
117
118
        $stats = $query->all();
119
        if ($stats) {
120
            // Compute the largest page load time
121
            $maxTotalPageLoad = 0;
122
            foreach ($stats as &$stat) {
123
                if (empty($stat['pageLoad'])) {
124
                    $pageLoad = $stat['craftTotalMs'];
125
                } else {
126
                    $pageLoad = $stat['pageLoad'];
127
                }
128
                if ($pageLoad > $maxTotalPageLoad) {
129
                    $maxTotalPageLoad = $pageLoad;
130
                }
131
            }
132
            // Massage the stats
133
            $index = 1;
134
            foreach ($stats as &$stat) {
135
                $stat['id'] = $index++;
136
                $stat['maxTotalPageLoad'] = $maxTotalPageLoad;
137
                // If there is no frontend beacon timing, use the Craft timing
138
                if (empty($stat['pageLoad'])) {
139
                    $stat['totalPageLoad'] = $stat['craftTotalMs'];
140
                } else {
141
                    $stat['totalPageLoad'] = $stat['pageLoad'];
142
                }
143
                // Decode any emojis in the title
144
                if (!empty($stat['title'])) {
145
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
146
                }
147
            }
148
            // Format the data for the API
149
            $data['data'] = $stats;
150
            $query = (new Query())
151
                ->from(['{{%webperf_data_samples}}'])
152
                ->groupBy('url');
153
            if ($filter !== '') {
154
                $query->where(['like', 'url', $filter]);
155
                $query->orWhere(['like', 'title', $filter]);
156
            }
157
            $count = $query->count();
158
            $data['links']['pagination'] = [
159
                'total' => $count,
160
                'per_page' => $per_page,
161
                'current_page' => $page,
162
                'last_page' => ceil($count / $per_page),
163
                'next_page_url' => null,
164
                'prev_page_url' => null,
165
                'from' => $offset + 1,
166
                'to' => $offset + ($count > $per_page ? $per_page : $count),
167
            ];
168
        }
169
170
        return $this->asJson($data);
171
    }
172
173
    /**
174
     * Handle requests for the dashboard redirects table
175
     *
176
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
177
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
178
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
179
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
180
     * @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...
181
     *
182
     * @return Response
183
     * @throws ForbiddenHttpException
184
     */
185
    public function actionRedirects(
186
        string $sort = 'hitCount|desc',
187
        int $page = 1,
188
        int $per_page = 20,
189
        $filter = '',
190
        $siteId = 0
191
    ): Response {
192
        PermissionHelper::controllerPermissionCheck('webperf:redirects');
193
        $data = [];
194
        $sortField = 'hitCount';
195
        $sortType = 'DESC';
196
        // Figure out the sorting type
197
        if ($sort !== '') {
198
            if (strpos($sort, '|') === false) {
199
                $sortField = $sort;
200
            } else {
201
                list($sortField, $sortType) = explode('|', $sort);
202
            }
203
        }
204
        // Query the db table
205
        $offset = ($page - 1) * $per_page;
206
        $query = (new Query())
207
            ->from(['{{%retour_static_redirects}}'])
208
            ->offset($offset)
209
            ->limit($per_page)
210
            ->orderBy("{$sortField} {$sortType}");
211
        if ((int)$siteId !== 0) {
212
            $query->where(['siteId' => $siteId]);
213
        }
214
        if ($filter !== '') {
215
            $query->where(['like', 'redirectSrcUrl', $filter]);
216
            $query->orWhere(['like', 'redirectDestUrl', $filter]);
217
        }
218
        $redirects = $query->all();
219
        // Add in the `deleteLink` field
220
        foreach ($redirects as &$redirect) {
221
            $redirect['deleteLink'] = UrlHelper::cpUrl('retour/delete-redirect/'.$redirect['id']);
222
            $redirect['editLink'] = UrlHelper::cpUrl('retour/edit-redirect/'.$redirect['id']);
223
        }
224
        // Format the data for the API
225
        if ($redirects) {
226
            $data['data'] = $redirects;
227
            $query = (new Query())
228
                ->from(['{{%retour_static_redirects}}']);
229
            if ($filter !== '') {
230
                $query->where(['like', 'redirectSrcUrl', $filter]);
231
                $query->orWhere(['like', 'redirectDestUrl', $filter]);
232
            }
233
            $count = $query->count();
234
            $data['links']['pagination'] = [
235
                'total' => $count,
236
                'per_page' => $per_page,
237
                'current_page' => $page,
238
                'last_page' => ceil($count / $per_page),
239
                'next_page_url' => null,
240
                'prev_page_url' => null,
241
                'from' => $offset + 1,
242
                'to' => $offset + ($count > $per_page ? $per_page : $count),
243
            ];
244
        }
245
246
        return $this->asJson($data);
247
    }
248
249
    // Protected Methods
250
    // =========================================================================
251
}
252