Passed
Push — master ( db1581...a5af1f )
by Ferry
04:30
created

CBController::validation()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php namespace crocodicstudio\crudbooster\controllers;
2
3
use crocodicstudio\crudbooster\controllers\scaffolding\traits\Join;
4
use crocodicstudio\crudbooster\exceptions\CBValidationException;
5
use crocodicstudio\crudbooster\models\ColumnModel;
6
use Illuminate\Database\Query\Builder;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\Log;
9
use Illuminate\Support\Facades\Validator;
10
use Illuminate\Support\Facades\Schema;
11
use crocodicstudio\crudbooster\controllers\scaffolding\traits\ColumnsRegister;
12
use crocodicstudio\crudbooster\controllers\traits\ControllerSetting;
13
14
class CBController extends Controller
15
{
16
    use ColumnsRegister, Join, ControllerSetting;
17
18
    private $assignmentData;
0 ignored issues
show
introduced by
The private property $assignmentData is not used, and could be removed.
Loading history...
19
20
    public function __construct()
21
    {
22
        columnSingleton()->newColumns();
23
        $this->cbInit();
24
        $this->data['columns'] = columnSingleton()->getColumns();
25
        view()->share($this->data);
26
    }
27
28
    public function __call($method, $parameters)
29
    {
30
        if($method == "getData") {
31
            $key = $parameters[0];
32
            if(isset($this->data[$key])) {
33
                return $this->data[$key];
34
            }else{
35
                return null;
36
            }
37
        }else{
38
            return null;
39
        }
40
    }
41
42
    private function repository()
43
    {
44
        $joins = columnSingleton()->getJoin();
45
        $columns = columnSingleton()->getColumns();
46
47
        $query = DB::table($this->data['table']);
48
49
50
        $query->addSelect($this->data['table'].'.'.cb()->pk($this->data['table']).' as primary_key');
51
52
        if(isset($this->data['hook_query_index']) && is_callable($this->data['hook_query_index']))
53
        {
54
            $query = call_user_func($this->data['hook_query_index'], $query);
55
        }
56
57
        $softDelete = isset($this->data['disable_soft_delete'])?$this->data['disable_soft_delete']:true;
58
        if($softDelete === true && Schema::hasColumn($this->data['table'],'deleted_at')) {
59
            $query->whereNull($this->data['table'].'.deleted_at');
60
        }
61
62
63
        if(isset($joins)) {
64
            foreach($joins as $join)
65
            {
66
                $query->join($join['target_table'],
67
                        $join['target_table_primary'],
68
                    $join['operator'],
69
                    $join['source_table_foreign'],
70
                    $join['type']);
71
            }
72
        }
73
74
        foreach($columns as $column) {
75
            /** @var ColumnModel $column */
76
            if(strpos($column->getField(),".") === false) {
77
                $query->addSelect($this->data['table'].'.'.$column->getField());
78
            }else{
79
                $query->addSelect($column->getField());
80
            }
81
82
            $query = getTypeHook($column->getType())->query($query, $column);
83
        }
84
85
        if(request()->has('q'))
86
        {
87
            if(isset($this->data['hook_search_query'])) {
88
                $query = call_user_func($this->data['hook_search_query'], $query);
89
            }else{
90
                $query->where(function ($where) use ($columns) {
91
                    /**
92
                     * @var $where Builder
93
                     */
94
                    foreach($columns as $column)
95
                    {
96
                        $where->orWhere($column['name'], 'like', '%'.request('q').'%');
0 ignored issues
show
Bug introduced by
Are you sure request('q') of type Illuminate\Http\Request|array|string 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

96
                        $where->orWhere($column['name'], 'like', '%'./** @scrutinizer ignore-type */ request('q').'%');
Loading history...
97
                    }
98
                });
99
            }
100
        }
101
102
        if(isset($this->data['hook_query_index']) && is_callable($this->data['hook_query_index'])) {
103
            $query = call_user_func($this->data['hook_query_index'], $query);
104
        }
105
106
107
        if(request()->has(['order_by','order_sort']))
108
        {
109
            if(in_array(request('order_by'),columnSingleton()->getColumnNameOnly())) {
110
                $query->orderBy(request('order_by'), request('order_sort'));
111
            }
112
        }else{
113
            if(isset($this->data['order_by'])) {
114
                $query->orderBy($this->data['order_by'][0], $this->data['order_by'][1]);
115
            }
116
        }
117
118
        return $query;
119
    }
120
121
    public function getIndex()
122
    {
123
        if(!module()->canBrowse()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
124
125
        $query = $this->repository();
126
        $result = $query->paginate(20);
127
        $data['result'] = $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
128
        return view("crudbooster::module.index.index", $data);
129
    }
130
131
132
    /**
133
     * @throws CBValidationException
134
     */
135
    private function validation()
136
    {
137
        if(isset($this->data['validation'])) {
138
            $validator = Validator::make(request()->all(), @$this->data['validation'], @$this->data['validation_messages']);
139
            if ($validator->fails()) {
140
                $message = $validator->messages();
141
                $message_all = $message->all();
142
                throw new CBValidationException(implode(', ',$message_all));
143
            }
144
        }
145
    }
146
147
    public function getAdd()
148
    {
149
        if(!module()->canCreate()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
150
151
        $data = [];
152
        $data['page_title'] = $this->data['page_title'].' : Add';
153
        $data['action_url'] = module()->addSaveURL();
154
        return view('crudbooster::module.form.form',$data);
155
    }
156
157
    public function postAddSave()
158
    {
159
        if(!module()->canCreate()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
160
161
        try {
162
            $this->validation();
163
            columnSingleton()->valueAssignment();
164
            $data = columnSingleton()->getAssignmentData();
165
166
            if(Schema::hasColumn($this->data['table'], 'created_at')) {
167
                $data['created_at'] = date('Y-m-d H:i:s');
168
            }
169
170
            $id = DB::table($this->data['table'])->insertGetId($data);
171
172
            if(isset($this->data['hook_after_insert']) && is_callable($this->data['hook_after_insert'])) {
173
                call_user_func($this->data['hook_after_insert'], $id);
174
            }
175
176
        } catch (CBValidationException $e) {
177
            Log::debug($e);
178
            return cb()->redirectBack($e->getMessage(),'info');
179
        } catch (\Exception $e) {
180
            Log::error($e);
181
            return cb()->redirectBack($e->getMessage(),'warning');
182
        }
183
184
        if (request('submit') == trans('crudbooster.button_save_more')) {
185
            return cb()->redirect(module()->addURL(), trans("crudbooster.alert_add_data_success"), 'success');
186
        } else {
187
            return cb()->redirect(module()->url(), trans("crudbooster.alert_add_data_success"), 'success');
188
        }
189
    }
190
191
    public function getEdit($id)
192
    {
193
        if(!module()->canUpdate()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
194
195
        $data = [];
196
        $data['row'] = $this->repository()->where($this->data['table'].'.'.getPrimaryKey($this->data['table']), $id)->first();
197
        $data['page_title'] = $this->data['page_title'].' : Edit';
198
        $data['action_url'] = module()->editSaveURL($id);
199
        return view('crudbooster::module.form.form', $data);
200
    }
201
202
    public function postEditSave($id)
203
    {
204
        if(!module()->canUpdate()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
205
206
        try {
207
            $this->validation();
208
            columnSingleton()->valueAssignment();
209
            $data = columnSingleton()->getAssignmentData();
210
            if(Schema::hasColumn($this->data['table'], 'updated_at')) {
211
                $data['updated_at'] = date('Y-m-d H:i:s');
212
            }
213
214
            if(isset($this->data['hook_before_update']) && is_callable($this->data['hook_before_update'])) {
215
                call_user_func($this->data['hook_before_update'], $id);
216
            }
217
218
            DB::table($this->data['table'])
219
                ->where(cb()->pk($this->data['table']), $id)
220
                ->update($data);
221
222
            if(isset($this->data['hook_after_update']) && is_callable($this->data['hook_after_update'])) {
223
                call_user_func($this->data['hook_after_update'], $id);
224
            }
225
226
        } catch (CBValidationException $e) {
227
            Log::debug($e);
228
            return cb()->redirectBack($e->getMessage(),'info');
229
        } catch (\Exception $e) {
230
            Log::error($e);
231
            return cb()->redirectBack($e->getMessage(),'warning');
232
        }
233
234
235
        if (request('submit') == trans('crudbooster.button_save_more')) {
236
            return cb()->redirectBack(trans("crudbooster.alert_update_data_success"), 'success');
237
        } else {
238
            return cb()->redirect(module()->url(), trans("crudbooster.alert_update_data_success"), 'success');
239
        }
240
    }
241
242
    public function getDelete($id)
243
    {
244
        if(!module()->canDelete()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
245
246
        if(isset($this->data['hook_before_delete']) && is_callable($this->data['hook_before_delete'])) {
247
            call_user_func($this->data['hook_before_delete'], $id);
248
        }
249
250
        $softDelete = isset($this->data['disable_soft_delete'])?$this->data['disable_soft_delete']:true;
251
252
        if ($softDelete === true && Schema::hasColumn($this->data['table'],'deleted_at')) {
253
            DB::table($this->data['table'])
254
                ->where(getPrimaryKey($this->data['table']), $id)
255
                ->update(['deleted_at' => date('Y-m-d H:i:s')]);
256
        } else {
257
            DB::table($this->data['table'])
258
                ->where(getPrimaryKey($this->data['table']), $id)
259
                ->delete();
260
        }
261
262
        if(isset($this->data['hook_after_delete']) && is_callable($this->data['hook_after_delete'])) {
263
            call_user_func($this->data['hook_after_delete'], $id);
264
        }
265
266
        return cb()->redirectBack(trans("crudbooster.alert_delete_data_success"), 'success');
267
    }
268
269
    public function getDetail($id)
270
    {
271
        if(!module()->canRead()) return cb()->redirect(cb()->getAdminUrl(),"You do not have access to this area");
272
273
        $data = [];
274
        $data['row'] = $this->repository()->where($this->data['table'].'.'.getPrimaryKey($this->data['table']), $id)->first();
275
        $data['page_title'] = $this->data['page_title'].' : Detail';
276
        return view('crudbooster::module.form.form_detail', $data);
277
    }
278
279
    public function postUploadFile()
280
    {
281
        if(auth()->guest()) return redirect(cb()->getLoginUrl());
282
283
        $file = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
284
        try {
285
286
            cb()->validation([
287
                'userfile' => 'required|mimes:' . config('crudbooster.UPLOAD_TYPES')
288
            ]);
289
290
            $file = cb()->uploadFile('userfile', true);
291
292
        } catch (CBValidationException $e) {
293
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
294
        } catch (\Exception $e) {
295
            return response()->json(['status'=>false,'message'=>$e->getMessage()]);
296
        }
297
298
        return response()->json([
299
            'status'=>true,
300
            'filename'=>basename($file),
301
            'full_url'=>asset($file),
302
            'url'=>$file
303
        ]);
304
    }
305
}
306