Passed
Pull Request — master (#1139)
by Iman
03:41
created

Index::index()   C

Complexity

Conditions 8
Paths 72

Size

Total Lines 74
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 42
nc 72
nop 1
dl 0
loc 74
rs 6.2894
c 0
b 0
f 0

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
namespace crocodicstudio\crudbooster\CBCoreModule;
4
5
use crocodicstudio\crudbooster\CBCoreModule\Index\FilterIndexRows;
6
use crocodicstudio\crudbooster\CBCoreModule\Index\CellContent;
7
use crocodicstudio\crudbooster\CBCoreModule\Index\Order;
8
use crocodicstudio\crudbooster\controllers\CBController;
9
use crocodicstudio\crudbooster\helpers\DbInspector;
10
use Illuminate\Support\Facades\Request;
11
use Illuminate\Support\Facades\DB;
12
use crocodicstudio\crudbooster\helpers\CRUDBooster;
13
use Schema;
14
15
class Index
16
{
17
    private $cb;
18
19
    private $table;
20
21
    public function index(CBController $CbCtrl)
22
    {
23
        $this->cb = $CbCtrl;
24
        $this->table = $CbCtrl->table;
25
26
        $data = [];
27
        if (request('parent_table')) {
28
            $data = $this->_handleParentTable();
29
        }
30
31
        $data['table'] = $CbCtrl->table;
32
        $tablePK = $data['table_pk'] = DbInspector::findPk($CbCtrl->table);
33
        $data['page_title'] = CRUDBooster::getCurrentModule()->name;
34
        $data['page_description'] = cbTrans('default_module_description');
35
        $data['date_candidate'] = $CbCtrl->date_candidate;
0 ignored issues
show
Bug introduced by
The property date_candidate does not seem to exist on crocodicstudio\crudboost...ontrollers\CBController.
Loading history...
36
        $data['limit'] = $limit = request('limit', $CbCtrl->limit);
37
38
39
        $result = $CbCtrl->table()->select(DB::raw($CbCtrl->table.".".$CbCtrl->primaryKey));
40
41
        $this->_filterForParent($result);
42
43
        $CbCtrl->hookQueryIndex($result);
44
45
        $tableCols = DbInspector::getTableCols($CbCtrl->table);
46
        $this->_filterOutSoftDeleted($tableCols, $result);
47
        unset($tableCols);
48
49
        $table = $CbCtrl->table;
50
        $columns_table = $CbCtrl->columns_table;
51
        foreach ($columns_table as $index => $coltab) {
52
            $field = @$coltab['name'];
53
54
            if (strpos($field, '.')) {
55
                $columns_table = $this->addDotField($columns_table, $index, $field, $result);
56
            } else {
57
                $columns_table = $this->_addField($columns_table, $index, $field, $result, $table);
58
            }
59
        }
60
61
        $this->_applyWhereAndQfilters($result, $columns_table, $table);
62
63
        $filter_is_orderby = false;
64
        if (request('filter_column')) {
65
            $filter_is_orderby = app(FilterIndexRows::class)->filterIndexRows($result, request('filter_column'));
66
        }
67
68
        if ($filter_is_orderby === true) {
69
            (new Order($this->cb))->handle($result, $table);
70
        }
71
        $data['result'] = $result->paginate($limit);
72
73
        $data['columns'] = $columns_table;
74
75
        if ($CbCtrl->index_return) {
76
            return $data;
77
        }
78
79
        //LISTING INDEX HTML
80
        $addAction = $CbCtrl->data['addaction'];
81
82
        if ($CbCtrl->sub_module) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $CbCtrl->sub_module of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
83
            $addAction = $this->_handleSubModules($addAction);
84
        }
85
86
        //$mainpath = CRUDBooster::mainpath();
87
        //$orig_mainpath = $CbCtrl->data['mainpath'];
88
        //$title_field = $CbCtrl->title_field;
89
        $number = (request('page', 1) - 1) * $limit + 1;
90
        $htmlContents = (new CellContent($CbCtrl))->calculate($data, $tablePK, $number, $columns_table, $table, $addAction); //end foreach data[result]
91
92
        $data['html_contents'] = ['html' => $htmlContents, 'data' => $data['result']];
93
94
        return $data;
95
    }
96
    /**
97
     * @return array
98
     */
99
    private function _handleParentTable()
100
    {
101
        $data = [];
102
        $data['parent_table'] = DB::table(request('parent_table'))->where(DbInspector::findPk(request('parent_table')), request('parent_id'))->first();
0 ignored issues
show
Bug introduced by
It seems like request('parent_table') can also be of type array; however, parameter $table of Illuminate\Support\Facades\DB::table() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

102
        $data['parent_table'] = DB::table(/** @scrutinizer ignore-type */ request('parent_table'))->where(DbInspector::findPk(request('parent_table')), request('parent_id'))->first();
Loading history...
103
        if (request('foreign_key')) {
104
            $data['parent_field'] = request('foreign_key');
105
        } else {
106
            $data['parent_field'] = DbInspector::getTableForeignKey(request('parent_table'), $this->table);
0 ignored issues
show
Unused Code introduced by
The call to crocodicstudio\crudboost...r::getTableForeignKey() has too many arguments starting with $this->table. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

106
            /** @scrutinizer ignore-call */ 
107
            $data['parent_field'] = DbInspector::getTableForeignKey(request('parent_table'), $this->table);

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. Please note the @ignore annotation hint above.

Loading history...
107
        }
108
109
        if (! $data['parent_field']) {
110
            return $data;
111
        }
112
113
        foreach ($this->cb->columns_table as $i => $col) {
114
            if ($col['name'] == $data['parent_field']) {
115
                unset($this->cb->columns_table[$i]);
116
            }
117
        }
118
119
        return $data;
120
    }
121
122
    /**
123
     * @param $result
124
     */
125
    private function _filterForParent($result)
126
    {
127
        if (! request('parent_id')) {
128
            return null;
129
        }
130
131
        $tableParent = CRUDBooster::parseSqlTable($this->table)['table'];
132
        $result->where($tableParent.'.'.request('foreign_key'), request('parent_id'));
0 ignored issues
show
Bug introduced by
Are you sure request('foreign_key') of type Illuminate\Http\Request|string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

132
        $result->where($tableParent.'.'./** @scrutinizer ignore-type */ request('foreign_key'), request('parent_id'));
Loading history...
133
    }
134
135
    /**
136
     * @param $tableColumns
137
     * @param $result
138
     */
139
    private function _filterOutSoftDeleted($tableColumns, $result)
140
    {
141
        if (! in_array('deleted_at', $tableColumns)) {
142
            return;
143
        }
144
        $result->where($this->table.'.deleted_at', '=', null);
145
    }
146
147
    /**
148
     * @param $result
149
     * @param $field
150
     * @param $columnsTable
151
     * @param $index
152
     * @return mixed
153
     */
154
    private function addDotField($columnsTable, $index, $field, $result)
155
    {
156
        $result->addselect($field.' as '.str_slug($field, '_'));
157
        $tableField = substr($field, 0, strpos($field, '.'));
158
        $fieldOrign = substr($field, strpos($field, '.') + 1);
159
        $columnsTable[$index]['type_data'] = DbInspector::getFieldTypes($tableField, $fieldOrign);
160
        $columnsTable[$index]['field'] = str_slug($field, '_');
161
        $columnsTable[$index]['field_raw'] = $field;
162
        $columnsTable[$index]['field_with'] = $tableField.'.'.$fieldOrign;
163
164
        return $columnsTable;
165
    }
166
167
    /**
168
     * @param $columnsTable
169
     * @param $index
170
     * @param $field
171
     * @param $table
172
     * @param $result
173
     * @return mixed
174
     */
175
    private function _addField($columnsTable, $index, $field, $result, $table)
176
    {
177
        $columnsTable[$index]['type_data'] = 'varchar';
178
        $columnsTable[$index]['field_with'] = null;
179
        $columnsTable[$index]['field'] = $field;
180
        $columnsTable[$index]['field_raw'] = $field;
181
182
        if (\Schema::hasColumn($table, $field)) {
183
            $result->addselect($table.'.'.$field);
184
            $columnsTable[$index]['type_data'] = DbInspector::getFieldTypes($table, $field);
185
            $columnsTable[$index]['field_with'] = $table.'.'.$field;
186
        }
187
188
        return $columnsTable;
189
    }
190
191
    /**
192
     * @param $result
193
     * @param $columnsTable
194
     * @param $table
195
     * @return mixed
196
     */
197
    private function _applyWhereAndQfilters($result, $columnsTable, $table)
198
    {
199
        if (request('q')) {
200
            $result->where(function ($query) use ($columnsTable) {
201
                foreach ($columnsTable as $col) {
202
                    if (! $col['field_with']) {
203
                        continue;
204
                    }
205
                    $query->orwhere($col['field_with'], "like", "%".request("q")."%");
0 ignored issues
show
Bug introduced by
Are you sure request('q') of type Illuminate\Http\Request|string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

205
                    $query->orwhere($col['field_with'], "like", "%"./** @scrutinizer ignore-type */ request("q")."%");
Loading history...
206
                }
207
            });
208
        }
209
210
        if (request('where')) {
211
            foreach (request('where') as $k => $v) {
212
                $result->where($table.'.'.$k, $v);
213
            }
214
        }
215
    }
216
217
    /**
218
     * @param $addAction
219
     * @return array
220
     */
221
    private function _handleSubModules($addAction)
222
    {
223
        foreach ($this->cb->sub_module as $module) {
224
            $addAction[] = [
225
                'label' => $module['label'],
226
                'icon' => $module['button_icon'],
227
                'url' => $this->subModuleUrl($module, CRUDBooster::parseSqlTable($this->table)['table']),
228
                'color' => $module['button_color'],
229
                'showIf' => $module['showIf'],
230
            ];
231
        }
232
233
        return $addAction;
234
    }
235
236
    /**
237
     * @param $module
238
     * @param $table_parent
239
     * @return string
240
     */
241
    private function subModuleUrl($module, $table_parent)
242
    {
243
        return CRUDBooster::adminPath($module['path']).'?parent_table='.$table_parent.'&parent_columns='
244
            .$module['parent_columns'].'&parent_columns_alias='
245
            .$module['parent_columns_alias'].'&parent_id=['
246
            .(! isset($module['custom_parent_id']) ? "id" : $module['custom_parent_id'])
247
            .']&return_url='.urlencode(Request::fullUrl()).'&foreign_key='
248
            .$module['foreign_key'].'&label='.urlencode($module['label']);
249
    }
250
251
}