Passed
Push — master ( 284e72...816a06 )
by Iman
04:12
created

Index::index()   C

Complexity

Conditions 9
Paths 144

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 42
nc 144
nop 1
dl 0
loc 75
rs 5.5094
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;
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 = \Schema::getColumnListing($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
        $limit = is_string($limit) ? (int)$limit : 15;
72
        $data['result'] = $result->paginate($limit);
73
74
        $data['columns'] = $columns_table;
75
76
        if ($CbCtrl->indexReturn) {
77
            return $data;
78
        }
79
80
        //LISTING INDEX HTML
81
        $addAction = $CbCtrl->data['addAction'];
82
83
        if (! empty($CbCtrl->sub_module)) {
84
            $addAction = $this->_handleSubModules($addAction);
85
        }
86
87
        //$mainpath = CRUDBooster::mainpath();
88
        //$orig_mainpath = $CbCtrl->data['mainpath'];
89
        //$titleField = $CbCtrl->titleField;
90
        $number = (request('page', 1) - 1) * $limit + 1;
91
        $htmlContents = (new CellContent($CbCtrl))->calculate($data, $tablePK, $number, $columns_table, $table, $addAction); //end foreach data[result]
92
93
        $data['html_contents'] = ['html' => $htmlContents, 'data' => $data['result']];
94
95
        return $data;
96
    }
97
98
    /**
99
     * @return array
100
     */
101
    private function _handleParentTable()
102
    {
103
        $data = [];
104
        $parent = (string)request('parent_table');
105
        $pk = DbInspector::findPk(request('parent_table'));
0 ignored issues
show
Bug introduced by
It seems like request('parent_table') can also be of type array; however, parameter $table of crocodicstudio\crudboost...s\DbInspector::findPK() 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

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

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