Passed
Push — master ( 7828f1...cb386f )
by Iman
03:40
created

Index::index()   F

Complexity

Conditions 10
Paths 288

Size

Total Lines 77
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 42
nc 288
nop 1
dl 0
loc 77
rs 3.913
c 0
b 0
f 0

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
namespace crocodicstudio\crudbooster\CBCoreModule;
4
5
use crocodicstudio\crudbooster\CBCoreModule\Index\FilterIndexRows;
6
use crocodicstudio\crudbooster\CBCoreModule\Index\RowContent;
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
        $table = $this->table = $CbCtrl->table;
25
26
        $data = [];
27
        if (request('parent_table')) {
28
            $data = $this->_handleParentTable();
29
        }
30
31
        $data['table'] = $CbCtrl->table;
32
        $data['table_pk'] = DbInspector::findPk($table);
33
        $data['page_title'] = CRUDBooster::getCurrentModule()->name;
34
        $data['page_description'] = cbTrans('default_module_description');
35
        //$data['date_candidate'] = $CbCtrl->date_candidate;
36
        $data['limit'] = $limit = request('limit', $CbCtrl->limit);
37
38
39
        $query = $CbCtrl->table()->select(DB::raw($table.".".$CbCtrl->primaryKey));
40
41
        $this->_filterForParent($query);
42
43
        $CbCtrl->hookQueryIndex($query);
44
45
        if (\Schema::hasColumn($table, 'deleted_at')) {
46
            $this->_filterOutSoftDeleted($query);
47
        }
48
49
        $columns_table = $CbCtrl->columns_table;
50
        foreach ($columns_table as $index => $coltab) {
51
            $field = @$coltab['name'];
52
53
            if (strpos($field, '.')) {
54
                $columns_table = $this->addDotField($columns_table, $index, $field, $query);
55
            } else {
56
                $columns_table = $this->_addField($columns_table, $index, $field, $query, $table);
57
            }
58
        }
59
60
        $this->_applyWhereAndQfilters($query, $columns_table, $table);
61
62
        $filter_is_orderby = false;
63
        if (request('filter_column')) {
64
            $filter_is_orderby = app(FilterIndexRows::class)->filterIndexRows($query, request('filter_column'));
65
        }
66
67
        if ($filter_is_orderby === true) {
68
            (new Order($this->cb))->handle($query, $table);
69
        }
70
        $limit = is_string($limit) ? (int)$limit : 15;
71
        $data['result'] = $query->paginate($limit);
72
73
        $data['columns'] = $columns_table;
74
75
        if ($CbCtrl->indexReturn) {
76
            return $data;
77
        }
78
79
        //LISTING INDEX HTML
80
        $addAction = $CbCtrl->data['addAction'];
81
82
        if (! empty($CbCtrl->sub_module)) {
83
            $addAction = $this->_handleSubModules($addAction);
84
        }
85
86
        //$mainpath = CRUDBooster::mainpath();
87
        //$orig_mainpath = $CbCtrl->data['mainpath'];
88
        //$titleField = $CbCtrl->titleField;
89
        $number = (request('page', 1) - 1) * $limit + 1;
90
        $columnsTable = array_filter($columns_table, function ($col) {
91
            return $col['visible'] !== false;
92
        });
93
        $htmlContents = (new RowContent($CbCtrl))->calculate($data, $number, $columnsTable, $addAction); //end foreach data[result]
94
95
        $data['html_contents'] = ['html' => $htmlContents, 'data' => $data['result']];
96
97
        return $data;
98
    }
99
100
    /**
101
     * @return array
102
     */
103
    private function _handleParentTable()
104
    {
105
        $data = [];
106
        $parent = (string)request('parent_table');
107
        $data['parent_table'] = CRUDBooster::first(request('parent_table'), request('parent_id'));
108
        if (request('foreign_key')) {
109
            $data['parent_field'] = request('foreign_key');
110
        } else {
111
            $data['parent_field'] = DbInspector::getRelatedTableName($parent);
112
        }
113
114
        if (! $data['parent_field']) {
115
            return $data;
116
        }
117
118
        foreach ($this->cb->columns_table as $i => $col) {
119
            if ($col['name'] == $data['parent_field']) {
120
                unset($this->cb->columns_table[$i]);
121
            }
122
        }
123
124
        return $data;
125
    }
126
127
    /**
128
     * @param $result
129
     */
130
    private function _filterForParent($result)
131
    {
132
        if (! request('parent_id')) {
133
            return null;
134
        }
135
136
        $tableParent = CRUDBooster::parseSqlTable($this->table)['table'];
137
        $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

137
        $result->where($tableParent.'.'./** @scrutinizer ignore-type */ request('foreign_key'), request('parent_id'));
Loading history...
138
    }
139
140
    /**
141
     * @param $result
142
     */
143
    private function _filterOutSoftDeleted($result)
144
    {
145
        $result->where($this->table.'.deleted_at', '=', null);
146
    }
147
148
    /**
149
     * @param $result
150
     * @param $field
151
     * @param $columnsTable
152
     * @param $index
153
     * @return mixed
154
     */
155
    private function addDotField($columnsTable, $index, $field, $result)
156
    {
157
        $result->addselect($field.' as '.str_slug($field, '_'));
158
        $tableField = substr($field, 0, strpos($field, '.'));
159
        $fieldOrign = substr($field, strpos($field, '.') + 1);
160
        $columnsTable[$index]['type_data'] = \Schema::getColumnType($tableField, $fieldOrign);
161
        $columnsTable[$index]['field'] = str_slug($field, '_');
162
        $columnsTable[$index]['field_raw'] = $field;
163
        $columnsTable[$index]['field_with'] = $tableField.'.'.$fieldOrign;
164
165
        return $columnsTable;
166
    }
167
168
    /**
169
     * @param $columnsTable
170
     * @param $index
171
     * @param $field
172
     * @param $table
173
     * @param $result
174
     * @return mixed
175
     */
176
    private function _addField($columnsTable, $index, $field, $result, $table)
177
    {
178
        $columnsTable[$index]['type_data'] = 'varchar';
179
        $columnsTable[$index]['field_with'] = null;
180
        $columnsTable[$index]['field'] = $field;
181
        $columnsTable[$index]['field_raw'] = $field;
182
183
        if (\Schema::hasColumn($table, $field)) {
184
            $result->addselect($table.'.'.$field);
185
            $columnsTable[$index]['type_data'] = \Schema::getColumnType($table, $field);
186
            $columnsTable[$index]['field_with'] = $table.'.'.$field;
187
        }
188
189
        return $columnsTable;
190
    }
191
192
    /**
193
     * @param $result
194
     * @param $columnsTable
195
     * @param $table
196
     * @return mixed
197
     */
198
    private function _applyWhereAndQfilters($result, $columnsTable, $table)
199
    {
200
        if (request('q')) {
201
            $result->where(function ($query) use ($columnsTable) {
202
                foreach ($columnsTable as $col) {
203
                    if (! $col['field_with']) {
204
                        continue;
205
                    }
206
                    $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

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