Passed
Push — develop ( 04e54c...316322 )
by Andrew
04:08
created

TablesController   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 272
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 30
eloc 161
dl 0
loc 272
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C actionPagesIndex() 0 114 15
C actionPageDetail() 0 115 15
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
                if (empty($stat['pageLoad'])) {
122
                    $pageLoad = $stat['craftTotalMs'];
123
                } else {
124
                    $pageLoad = $stat['pageLoad'];
125
                }
126
                if ($pageLoad > $maxTotalPageLoad) {
127
                    $maxTotalPageLoad = $pageLoad;
128
                }
129
            }
130
            // Massage the stats
131
            $index = 1;
132
            foreach ($stats as &$stat) {
133
                $stat['id'] = $index++;
134
                $stat['maxTotalPageLoad'] = $maxTotalPageLoad;
135
                // If there is no frontend beacon timing, use the Craft timing
136
                if (empty($stat['pageLoad'])) {
137
                    $stat['totalPageLoad'] = $stat['craftTotalMs'];
138
                } else {
139
                    $stat['totalPageLoad'] = $stat['pageLoad'];
140
                }
141
                // Decode any emojis in the title
142
                if (!empty($stat['title'])) {
143
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
144
                }
145
            }
146
            // Format the data for the API
147
            $data['data'] = $stats;
148
            $query = (new Query())
149
                ->from(['{{%webperf_data_samples}}'])
150
                ->groupBy('url');
151
            if ($filter !== '') {
152
                $query->where(['like', 'url', $filter]);
153
                $query->orWhere(['like', 'title', $filter]);
154
            }
155
            $count = $query->count();
156
            $data['links']['pagination'] = [
157
                'total' => $count,
158
                'per_page' => $per_page,
159
                'current_page' => $page,
160
                'last_page' => ceil($count / $per_page),
161
                'next_page_url' => null,
162
                'prev_page_url' => null,
163
                'from' => $offset + 1,
164
                'to' => $offset + ($count > $per_page ? $per_page : $count),
165
            ];
166
        }
167
168
        return $this->asJson($data);
169
    }
170
171
    /**
172
     * Handle requests for the dashboard statistics table
173
     *
174
     * @param string $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
175
     * @param int    $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
176
     * @param int    $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
177
     * @param string $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
178
     * @param string $pageUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
179
     * @param int    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
180
     *
181
     * @return Response
182
     * @throws ForbiddenHttpException
183
     */
184
    public function actionPageDetail(
185
        string $sort = 'pageLoad|desc',
186
        int $page = 1,
187
        int $per_page = 20,
188
        $filter = '',
189
        $pageUrl = '',
190
        $siteId = 0
191
    ): Response {
192
        PermissionHelper::controllerPermissionCheck('webperf:pages');
193
        $data = [];
194
        $sortField = 'pageLoad';
195
        $sortType = 'DESC';
196
        $pageUrl = urldecode($pageUrl);
197
        // Figure out the sorting type
198
        if ($sort !== '') {
199
            if (strpos($sort, '|') === false) {
200
                $sortField = $sort;
201
            } else {
202
                list($sortField, $sortType) = explode('|', $sort);
203
            }
204
        }
205
        if ($sortField === 'totalPageLoad') {
206
            $sortField = 'pageLoad';
207
        }
208
        // Query the db table
209
        $offset = ($page - 1) * $per_page;
210
        $query = (new Query())
211
            ->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...
212
                'url',
213
                'title',
214
                'pageLoad',
215
                'domInteractive',
216
                'firstContentfulPaint',
217
                'firstPaint',
218
                'firstByte',
219
                'connect',
220
                'dns',
221
                'craftTotalMs',
222
                'craftDbCnt',
223
                'craftDbMs',
224
                'craftTwigCnt',
225
                'craftTwigMs',
226
                'craftTotalMemory',
227
            ])
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...
228
            ->from(['{{%webperf_data_samples}}'])
229
            ->offset($offset)
230
            ->where(['url' => $pageUrl])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
231
        ;
232
        if ((int)$siteId !== 0) {
233
            $query->where(['siteId' => $siteId]);
234
        }
235
        if ($filter !== '') {
236
            $query
237
                ->where(['like', 'url', $filter])
238
                ->orWhere(['like', 'title', $filter])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
239
            ;
240
        }
241
        $query
242
            ->orderBy("{$sortField} {$sortType}")
243
            ->limit($per_page)
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
244
        ;
245
246
        $stats = $query->all();
247
        if ($stats) {
248
            // Compute the largest page load time
249
            $maxTotalPageLoad = 0;
250
            foreach ($stats as &$stat) {
251
                if (empty($stat['pageLoad'])) {
252
                    $pageLoad = $stat['craftTotalMs'];
253
                } else {
254
                    $pageLoad = $stat['pageLoad'];
255
                }
256
                if ($pageLoad > $maxTotalPageLoad) {
257
                    $maxTotalPageLoad = $pageLoad;
258
                }
259
            }
260
            // Massage the stats
261
            $index = 1;
262
            foreach ($stats as &$stat) {
263
                $stat['id'] = $index++;
264
                $stat['maxTotalPageLoad'] = $maxTotalPageLoad;
265
                // If there is no frontend beacon timing, use the Craft timing
266
                if (empty($stat['pageLoad'])) {
267
                    $stat['totalPageLoad'] = $stat['craftTotalMs'];
268
                } else {
269
                    $stat['totalPageLoad'] = $stat['pageLoad'];
270
                }
271
                // Decode any emojis in the title
272
                if (!empty($stat['title'])) {
273
                    $stat['title'] = html_entity_decode($stat['title'], ENT_NOQUOTES, 'UTF-8');
274
                }
275
            }
276
            // Format the data for the API
277
            $data['data'] = $stats;
278
            $query = (new Query())
279
                ->from(['{{%webperf_data_samples}}'])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
280
                ;
281
            if ($filter !== '') {
282
                $query->where(['like', 'url', $filter]);
283
                $query->orWhere(['like', 'title', $filter]);
284
            }
285
            $count = $query->count();
286
            $data['links']['pagination'] = [
287
                'total' => $count,
288
                'per_page' => $per_page,
289
                'current_page' => $page,
290
                'last_page' => ceil($count / $per_page),
291
                'next_page_url' => null,
292
                'prev_page_url' => null,
293
                'from' => $offset + 1,
294
                'to' => $offset + ($count > $per_page ? $per_page : $count),
295
            ];
296
        }
297
298
        return $this->asJson($data);
299
    }
300
301
    // Protected Methods
302
    // =========================================================================
303
}
304