Completed
Push — master ( aed5b3...caff4d )
by Michal
05:21
created

ReportsController::data_tables()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 94
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 94
rs 8.4378
c 0
b 0
f 0
ccs 42
cts 42
cp 1
cc 3
eloc 61
nc 3
nop 0
crap 3

How to fix   Long Method   

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
/* vim: set expandtab sw=4 ts=4 sts=4: */
4
/**
5
 * Reports controller handling reports creation and rendering.
6
 *
7
 * phpMyAdmin Error reporting server
8
 * Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
15
 * @license   https://opensource.org/licenses/mit-license.php MIT License
16
 *
17
 * @see      https://www.phpmyadmin.net/
18
 */
19
20
namespace App\Controller;
21
22
use App\Utility\Sanitize;
23
use Cake\Core\Configure;
24
use Cake\Log\Log;
25
use Cake\Network\Exception\NotFoundException;
26
use Cake\ORM\TableRegistry;
27
28
/**
29
 * Reports controller handling reports modification and rendering.
30
 */
31
class ReportsController extends AppController
32
{
33
    public $components = array('RequestHandler', 'OrderSearch');
34
35
    public $helpers = array('Html', 'Form', 'Reports', 'Incidents');
36
    public $uses = array('Incidents', 'Reports', 'Notifications', 'Developers');
37
38 1
    public function index()
39
    {
40 1
        $this->Reports->recursive = -1;
41 1
        $this->set('distinct_statuses',
42 1
            $this->_findArrayList($this->Reports->find()->select(array('status'))->distinct(array('status')),
43 1
            'status')
44
        );
45 1
        $this->set('distinct_versions',
46 1
            $this->_findArrayList($this->Reports->find()->select(array('pma_version'))->distinct(array('pma_version')), 'pma_version')
47
        );
48 1
        $this->set('distinct_error_names',
49 1
            $this->_findArrayList($this->Reports->find('all', array(
50 1
                'fields' => array('error_name'),
51
                'conditions' => array('error_name !=' => ''),
52 1
            ))->distinct(array('error_name')), 'error_name')
53
        );
54 1
        $this->set('statuses', $this->Reports->status);
55 1
        $this->autoRender = true;
56 1
    }
57
58 1
    public function view($reportId)
59
    {
60 1
        if (!$reportId) {
61
            throw new NotFoundException(__('Invalid Report'));
62
        }
63 1
        $report = $this->Reports->findById($reportId)->toArray();
64 1
        if (!$report) {
65 1
            throw new NotFoundException(__('Invalid Report'));
66
        }
67
68 1
        $this->set('report', $report);
69 1
        $this->set('project_name', Configure::read('GithubRepoPath'));
70 1
        $this->Reports->id = $reportId;
71 1
        $this->set('incidents', $this->Reports->getIncidents()->toArray());
72 1
        $this->set('incidents_with_description',
73 1
            $this->Reports->getIncidentsWithDescription());
74 1
        $this->set('incidents_with_stacktrace',
75 1
            $this->Reports->getIncidentsWithDifferentStacktrace());
76 1
        $this->set('related_reports', $this->Reports->getRelatedReports());
77 1
        $this->set('status', $this->Reports->status);
78 1
        $this->_setSimilarFields($reportId);
79
80
        // if there is an unread notification for this report, then mark it as read
81 1
        $current_developer = TableRegistry::get('Developers')->
82 1
                    findById($this->request->session()->read('Developer.id'))->all()->first();
83
        //$current_developer = Sanitize::clean($current_developer);
84 1
        if ($current_developer) {
85 1
            TableRegistry::get('Notifications')->deleteAll(
86 1
                array('developer_id' => $current_developer['Developer']['id'],
87 1
                    'report_id' => $reportId,
88
                ),
89 1
                false
0 ignored issues
show
Unused Code introduced by
The call to Table::deleteAll() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
90
            );
91
        }
92 1
    }
93
94 1
    public function data_tables()
95
    {
96
        $subquery_params = array(
97 1
            'fields' => array(
98
                'report_id' => 'report_id',
99
                'inci_count' => 'COUNT(id)',
100
                ),
101
            'group' => 'report_id',
102
        );
103 1
        $subquery = TableRegistry::get('incidents')->find('all', $subquery_params);
104
105
        // override automatic aliasing, for proper usage in joins
106
        $aColumns = array(
107 1
            'id' => 'id',
108
            'error_name' => 'error_name',
109
            'error_message' => 'error_message',
110
            'pma_version' => 'pma_version',
111
            'status' => 'status',
112
            'exception_type' => 'exception_type',
113
            'inci_count' => 'inci_count',
114
        );
115
116 1
        $searchConditions = $this->OrderSearch->getSearchConditions($aColumns);
117 1
        $orderConditions = $this->OrderSearch->getOrder($aColumns);
118
119
        $params = array(
120 1
            'fields' => $aColumns,
121
            'conditions' => array(
122 1
                    $searchConditions,
123 1
                    'related_to is NULL',
124
                ),
125 1
            'order' => $orderConditions,
126
        );
127
128 1
        $pagedParams = $params;
129 1
        $pagedParams['limit'] = intval($this->request->query('iDisplayLength'));
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Http\ServerRequest::query() has been deprecated with message: 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
130 1
        $pagedParams['offset'] = intval($this->request->query('iDisplayStart'));
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Http\ServerRequest::query() has been deprecated with message: 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
131
132 1
        $rows = $this->_findAllDataTable(
133 1
            $this->Reports->find('all', $pagedParams)->innerJoin(
134 1
                array('incidents' => $subquery), array('incidents.report_id = Reports.id')
135
            )
136
        );
137
        //$rows = Sanitize::clean($rows);
138 1
        $totalFiltered = $this->Reports->find('all', $params)->count();
139
140
        // change exception_type from boolean values to strings
141
        // add incident count for related reports
142 1
        $dispRows = array();
143 1
        foreach ($rows as $row) {
144 1
            $row[4] = $this->Reports->status[$row[4]];
145 1
            $row[5] = (intval($row[5])) ? ('php') : ('js');
146
            $input_elem = "<input type='checkbox' name='reports[]' value='"
147 1
                . $row[0]
148 1
                . "'/>";
149
150
            $subquery_params_count = array(
151 1
                'fields' => array(
152
                    'report_id' => 'report_id',
153
                ),
154
            );
155 1
            $subquery_count = TableRegistry::get('incidents')->find(
156 1
                'all', $subquery_params_count
157
            );
158
159
            $params_count = array(
160 1
                'fields' => array('inci_count' => 'inci_count'),
161
                'conditions' => array(
162 1
                        'related_to = ' . $row[0],
163
                ),
164
            );
165
166 1
            $inci_count_related = $this->Reports->find('all', $params_count)->innerJoin(
167 1
                array('incidents' => $subquery_count),
168 1
                array('incidents.report_id = Reports.related_to')
169 1
            )->count();
170
171 1
            $row[6] += $inci_count_related;
172
173 1
            array_unshift($row, $input_elem);
174 1
            array_push($dispRows, $row);
175
        }
176
177
        $response = array(
178 1
            'iTotalRecords' => $this->Reports->find('all')->count(),
179 1
            'iTotalDisplayRecords' => $totalFiltered,
180 1
            'sEcho' => intval($this->request->query('sEcho')),
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Http\ServerRequest::query() has been deprecated with message: 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
181 1
            'aaData' => $dispRows,
182
        );
183 1
        $this->autoRender = false;
184 1
        $this->response->body(json_encode($response));
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Http\Response::body() has been deprecated with message: 3.4.0 Mutable response methods are deprecated. Use `withBody()` and `getBody()` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
185
186 1
        return $this->response;
187
    }
188
189
    public function mark_related_to($reportId)
190
    {
191
        $relatedTo = $this->request->query('related_to');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\Http\ServerRequest::query() has been deprecated with message: 3.4.0 Use getQuery() or the PSR-7 getQueryParams() and withQueryParams() methods instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
192
        if (!$reportId
193
            || !$relatedTo
194
            || $reportId == $relatedTo
195
        ) {
196
            throw new NotFoundException(__('Invalid Report'));
197
        }
198
199
        $report = $this->Reports->get($reportId);
200
        if (!$report) {
201
            throw new NotFoundException(__('Invalid Report'));
202
        }
203
204
        $this->Reports->addToRelatedGroup($report, $relatedTo);
205
206
        $flash_class = 'alert alert-success';
207
        $this->Flash->default('This report has been marked the same as #'
208
                . $relatedTo,
209
                array('params' => array('class' => $flash_class)));
210
        $this->redirect("/reports/view/$reportId");
211
    }
212
213
    public function unmark_related_to($reportId)
214
    {
215
        if (!$reportId) {
216
            throw new NotFoundException(__('Invalid Report'));
217
        }
218
219
        $report = $this->Reports->get($reportId);
220
        if (!$report) {
221
            throw new NotFoundException(__('Invalid Report'));
222
        }
223
224
        $this->Reports->removeFromRelatedGroup($report);
225
226
        $flash_class = 'alert alert-success';
227
        $this->Flash->default('This report has been marked as different.',
228
            array('params' => array('class' => $flash_class)));
229
        $this->redirect("/reports/view/$reportId");
230
    }
231
232
    public function change_state($reportId)
233
    {
234
        if (!$reportId) {
235
            throw new NotFoundException(__('Invalid Report'));
236
        }
237
238
        $report = $this->Reports->get($reportId);
239
        if (!$report) {
240
            throw new NotFoundException(__('Invalid Report'));
241
        }
242
243
        $state = $this->request->data['state'];
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Http\ServerRequest::$data has been deprecated with message: 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
244
        $newState = $this->Reports->status[$state];
245
        if (!$newState) {
246
            throw new NotFoundException(__('Invalid State'));
247
        }
248
        $report->status = $state;
249
        $this->Reports->save($report);
250
251
        $flash_class = 'alert alert-success';
252
        $this->Flash->default('The state has been successfully changed.',
253
            array('params' => array('class' => $flash_class)));
254
        $this->redirect("/reports/view/$reportId");
255
    }
256
257
    /**
258
     * To carry out mass actions on Reports
259
     * Currently only to change their statuses.
260
     * Can be Extended for other mass operations as well.
261
     * Expects an array of Report Ids as a POST parameter.
262
     */
263
    public function mass_action()
264
    {
265
        $flash_class = 'alert alert-error';
266
        $state = $this->request->data['state'];
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Http\ServerRequest::$data has been deprecated with message: 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
267
        $newState = $this->Reports->status[$state];
268
        if (!$newState) {
269
            Log::write(
270
                'error',
271
                'ERRORED: Invalid param "state" in ReportsController::mass_action()',
272
                'alert'
273
            );
274
            $msg = 'ERROR: Invalid State!!';
275
        } elseif (count($this->request->data['reports']) == 0) {
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Http\ServerRequest::$data has been deprecated with message: 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
276
            $msg = 'No Reports Selected!! Please Select Reports and try again.';
277
        } else {
278
            $msg = "Status has been changed to '"
279
                . $this->request->data['state']
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Http\ServerRequest::$data has been deprecated with message: 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
280
                . "' for selected Reports!";
281
            $flash_class = 'alert alert-success';
282
            foreach ($this->request->data['reports'] as $report_id) {
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Http\ServerRequest::$data has been deprecated with message: 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
283
                $report = $this->Reports->get($report_id);
284
                if (!$report) {
285
                    Log::write(
286
                        'error',
287
                        'ERRORED: Invalid report_id in ReportsController::mass_action()',
288
                        'alert'
289
                    );
290
                    $msg = 'ERROR:Invalid Report ID:' . $report_id;
291
                    $flash_class = 'alert alert-error';
292
                    break;
293
                }
294
                $report->status = $state;
295
                $this->Reports->save($report);
296
            }
297
        }
298
299
        $this->Flash->default($msg,
300
            array('params' => array('class' => $flash_class)));
301
        $this->redirect('/reports/');
302
    }
303
304
    //# HELPERS
305
306 1
    protected function _setSimilarFields($id)
307
    {
308 1
        $this->Reports->id = $id;
309
310 1
        $this->set('columns', TableRegistry::get('Incidents')->summarizableFields);
311 1
        $relatedEntries = array();
312
313 1
        foreach (TableRegistry::get('Incidents')->summarizableFields as $field) {
314
            list($entriesWithCount, $totalEntries) =
315 1
                    $this->Reports->getRelatedByField($field, 25, true);
316 1
            $relatedEntries[$field] = $entriesWithCount;
317 1
            $this->set("${field}_distinct_count", $totalEntries);
318
        }
319
        //error_log(json_encode($relatedEntries));
320
        $this->set('related_entries', $relatedEntries);
321
    }
322
323
    protected function _findArrayList($results, $key)
324
    {
325 1
        $output = array();
326 1
        foreach ($results as $row) {
327 1
            $output[] = $row[$key];
328
        }
329
330 1
        return $output;
331
    }
332
333
    protected function _findAllDataTable($results)
334
    {
335 1
        $output = array();
336 1
        foreach ($results as $row) {
337 1
            $output_row = array();
338 1
            $row = $row->toArray();
339 1
            foreach ($row as $key => $value) {
340 1
                $output_row[] = $value;
341
            }
342 1
            $output[] = $output_row;
343
        }
344
345 1
        return $output;
346
    }
347
}
348