Passed
Push — master ( 38a665...decd12 )
by Ferry
05:33
created

CB::urlFilterColumn()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 24
c 0
b 0
f 0
rs 8.8333
cc 7
nc 4
nop 4
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use Illuminate\Http\File;
6
use Illuminate\Support\Facades\Cache;
7
use crocodicstudio\crudbooster\exceptions\CBValidationException;
8
use Illuminate\Support\Facades\DB;
9
use Illuminate\Support\Facades\Config;
10
use Illuminate\Validation\ValidationException;
11
use Image;
12
use Request;
13
use Route;
14
use Illuminate\Support\Facades\Schema;
15
use Illuminate\Support\Facades\Session;
16
use Illuminate\Support\Facades\Storage;
17
use Validator;
18
19
class CB
20
{
21
22
    public function getRoleByName($roleName) {
23
        return $this->find("cb_roles",['name'=>$roleName]);
24
    }
25
26
    public function fcm() {
27
        return new FCM();
28
    }
29
30
    public function sidebar() {
31
        return new SidebarMenus();
32
    }
33
34
    public function session() {
35
        return new UserSession();
36
    }
37
38
    public function getDeveloperUrl($path = null) {
39
        $path = ($path)?"/".trim($path,"/"):null;
40
        return url("developer/".getSetting("developer_path")).$path;
41
    }
42
43
    public function getProfileUrl() {
44
        return $this->getAdminUrl()."/profile";
45
    }
46
47
    public function getLogoutUrl() {
48
        return $this->getAdminUrl()."/logout";
49
    }
50
51
    public function getLoginUrl() {
52
        return $this->getAdminUrl("login");
53
    }
54
55
    public function getAdminUrl($path = null) {
56
        $path = ($path)?"/".trim($path,"/"):null;
57
        return url(cbConfig("ADMIN_PATH")).$path;
0 ignored issues
show
Bug introduced by
Are you sure url(cbConfig('ADMIN_PATH')) of type Illuminate\Contracts\Routing\UrlGenerator|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

57
        return /** @scrutinizer ignore-type */ url(cbConfig("ADMIN_PATH")).$path;
Loading history...
58
    }
59
60
    public function getAppName() {
61
        return env("APP_NAME","CRUDBOOSTER");
62
    }
63
64
    /**
65
     * @param $filename
66
     * @param $extension
67
     * @param null $resize_width
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_width is correct as it would always require null to be passed?
Loading history...
68
     * @param null $resize_height
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_height is correct as it would always require null to be passed?
Loading history...
69
     * @return string
70
     * @throws \Exception
71
     */
72
    private function uploadFileProcess($filename, $extension, $encrypt = true, $resize_width = null, $resize_height = null)
0 ignored issues
show
Unused Code introduced by
The parameter $filename is not used and could be removed. ( Ignorable by Annotation )

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

72
    private function uploadFileProcess(/** @scrutinizer ignore-unused */ $filename, $extension, $encrypt = true, $resize_width = null, $resize_height = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
    {
74
        if(in_array($extension,cbConfig("UPLOAD_FILE_EXTENSION_ALLOWED"))) {
75
            $filename = slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file seems to be never defined.
Loading history...
76
            $file_path = cbConfig("UPLOAD_PATH_FORMAT");
77
            $file_path = str_replace("{Y}",date('Y'), $file_path);
78
            $file_path = str_replace("{m}", date('m'), $file_path);
79
            $file_path = str_replace("{d}", date("d"), $file_path);
80
81
            //Create Directory Base On Template
82
            Storage::makeDirectory($file_path);
83
            Storage::put($file_path."/index.html","&nbsp;","public");
84
            Storage::put($file_path."/.gitignore","!.gitignore","public");
85
86
            if ($encrypt == true) {
87
                $filename = md5(strRandom(5)).'.'.$extension;
88
            } else {
89
                $filename = slug($filename, '_').'.'.$extension;
90
            }
91
92
            if($resize_width || $resize_height) {
0 ignored issues
show
introduced by
$resize_height is of type null, thus it always evaluated to false.
Loading history...
93
                $this->resizeImage($file, $file_path.'/'.$filename, $resize_width, $resize_height);
94
                return $file_path.'/'.$filename;
95
            }else{
96
                if (Storage::put($file_path.'/'.$filename, $file, 'public')) {
97
                    return $file_path.'/'.$filename;
98
                } else {
99
                    throw new \Exception("Something went wrong, file can't upload!");
100
                }
101
            }
102
        }else{
103
            throw new \Exception("The file format is not allowed!");
104
        }
105
    }
106
107
    /**
108
     * @param $base64_value
109
     * @param bool $encrypt
110
     * @param null $resize_width
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_width is correct as it would always require null to be passed?
Loading history...
111
     * @param null $resize_height
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_height is correct as it would always require null to be passed?
Loading history...
112
     * @throws \Exception
113
     */
114
    public function uploadBase64($filename, $base64_value, $encrypt = true, $resize_width = null, $resize_height = null)
115
    {
116
        $fileData = base64_decode($base64_value);
117
        $mime_type = finfo_buffer(finfo_open(), $fileData, FILEINFO_MIME_TYPE);
118
        if($mime_type) {
119
            if($mime_type = explode('/', $mime_type)) {
120
                $ext = $mime_type[1];
121
                if($filename && $ext) {
122
                    return $this->uploadFileProcess($filename, $ext, $encrypt, $resize_width, $resize_height);
123
                }
124
            }else {
125
                throw new \Exception("Mime type not found");
126
            }
127
        }else{
128
            throw new \Exception("Mime type not found");
129
        }
130
    }
131
132
    /**
133
     * @param $name
134
     * @param bool $encrypt
135
     * @param int $resize_width
136
     * @param null $resize_height
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_height is correct as it would always require null to be passed?
Loading history...
137
     * @return string
138
     * @throws \Exception
139
     */
140
    public function uploadFile($name, $encrypt = true, $resize_width = null, $resize_height = null)
141
    {
142
        if (request()->hasFile($name)) {
143
            $file = request()->file($name);
144
            $filename = $file->getClientOriginalName();
145
            $ext = strtolower($file->getClientOriginalExtension());
146
147
            if($filename && $ext) {
148
                return $this->uploadFileProcess($filename, $ext, $encrypt, $resize_width, $resize_height);
0 ignored issues
show
Bug introduced by
It seems like $resize_width can also be of type integer; however, parameter $resize_width of crocodicstudio\crudboost...CB::uploadFileProcess() does only seem to accept null, 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

148
                return $this->uploadFileProcess($filename, $ext, $encrypt, /** @scrutinizer ignore-type */ $resize_width, $resize_height);
Loading history...
149
            }
150
151
        } else {
152
            throw new \Exception("There is no file send to server!");
153
        }
154
    }
155
156
    /**
157
     * @param $file
158
     * @param $fullFilePath
159
     * @param null $resize_width
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_width is correct as it would always require null to be passed?
Loading history...
160
     * @param null $resize_height
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $resize_height is correct as it would always require null to be passed?
Loading history...
161
     * @param int $qty
162
     * @param int $thumbQty
163
     * @throws \Exception
164
     */
165
    public function resizeImage($file, $fullFilePath, $resize_width = null, $resize_height = null, $qty = 100, $thumbQty = 75)
0 ignored issues
show
Unused Code introduced by
The parameter $thumbQty is not used and could be removed. ( Ignorable by Annotation )

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

165
    public function resizeImage($file, $fullFilePath, $resize_width = null, $resize_height = null, $qty = 100, /** @scrutinizer ignore-unused */ $thumbQty = 75)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
166
    {
167
        $images_ext = cbConfig("UPLOAD_IMAGE_EXTENSION_ALLOWED");
168
169
        $filename = basename($fullFilePath);
170
        $file_path = trim(str_replace($filename, '', $fullFilePath), '/');
0 ignored issues
show
Unused Code introduced by
The assignment to $file_path is dead and can be removed.
Loading history...
171
        $ext = pathinfo($fullFilePath, PATHINFO_EXTENSION);
172
173
        if (in_array(strtolower($ext), $images_ext)) {
174
175
            // Upload file
176
            $img = Image::make($file);
177
            $img->encode($ext, $qty);
178
179
            if ($resize_width && $resize_height) {
0 ignored issues
show
introduced by
$resize_width is of type null, thus it always evaluated to false.
Loading history...
180
                $img->fit($resize_width, $resize_height);
181
182
            } elseif ($resize_width && ! $resize_height) {
0 ignored issues
show
introduced by
$resize_width is of type null, thus it always evaluated to false.
Loading history...
183
184
                $img->resize($resize_width, null, function ($constraint) {
185
                    $constraint->aspectRatio();
186
                });
187
188
            } elseif (! $resize_width && $resize_height) {
0 ignored issues
show
introduced by
$resize_height is of type null, thus it always evaluated to false.
Loading history...
introduced by
$resize_width is of type null, thus it always evaluated to false.
Loading history...
189
190
                $img->resize(null, $resize_height, function ($constraint) {
191
                    $constraint->aspectRatio();
192
                });
193
194
            } else {
195
196
                if ($img->width() > cbConfig("DEFAULT_IMAGE_MAX_WIDTH_RES")) {
197
                    $img->resize(cbConfig("DEFAULT_IMAGE_MAX_WIDTH_RES"), null, function ($constraint) {
198
                        $constraint->aspectRatio();
199
                    });
200
                }
201
            }
202
203
            Storage::put($fullFilePath, $img, 'public');
204
        }else{
205
            throw new \Exception("The file format is not allowed!");
206
        }
207
    }
208
209
    public function update($table, $id, $data)
210
    {
211
        DB::table($table)
212
            ->where($this->pk($table), $id)
213
            ->update($data);
214
    }
215
216
    public function updateCompact($table, $id, $params) {
217
        $data = [];
218
        foreach ($params as $param) {
219
            $data[$param] = request($param);
220
        }
221
        $this->update($table, $id, $data);
222
    }
223
224
    public function find($table, $id)
225
    {
226
        if (is_array($id)) {
227
            $first = DB::table($table);
228
            foreach ($id as $k => $v) {
229
                $first->where($k, $v);
230
            }
231
232
            return $first->first();
233
        } else {
234
            $pk = $this->pk($table);
235
236
            return DB::table($table)->where($pk, $id)->first();
237
        }
238
    }
239
240
    public function listAllTable()
241
    {
242
        return DB::connection()->getDoctrineSchemaManager()->listTableNames();
243
    }
244
245
    public function listAllColumns($table)
246
    {
247
        return Schema::getColumnListing($table);
248
    }
249
250
    public function findAll($table, $condition_array = [])
251
    {
252
        return DB::table($table)->where($condition_array)->get();
253
    }
254
255
    public function redirectBack($message, $type = 'warning')
256
    {
257
        if (request()->ajax()) {
258
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $_SERVER['HTTP_REFERER']]);
259
        } else {
260
            return redirect()->back()->withInput()
261
                ->with(['message'=> $message, 'message_type'=> $type]);
262
        }
263
    }
264
265
    public function redirect($to, $message, $type = 'warning')
266
    {
267
        if (Request::ajax()) {
268
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]);
269
        } else {
270
            return redirect($to)->with(['message' => $message, 'message_type' => $type]);
271
        }
272
    }
273
274
275
    public function getCurrentMethod()
276
    {
277
        $action = str_replace("App\Http\Controllers", "", Route::currentRouteAction());
278
        $atloc = strpos($action, '@') + 1;
279
        $method = substr($action, $atloc);
280
281
        return $method;
282
    }
283
284
    public function stringBetween($string, $start, $end)
285
    {
286
        $string = ' '.$string;
287
        $ini = strpos($string, $start);
288
        if ($ini == 0) {
289
            return '';
290
        }
291
        $ini += strlen($start);
292
        $len = strpos($string, $end, $ini) - $ini;
293
294
        return substr($string, $ini, $len);
295
    }
296
297
    /**
298
     * @param array $rules
299
     * @param array $messages
300
     * @throws CBValidationException
301
     */
302
    public function validation($rules = [], $messages = [])
303
    {
304
        $input_arr = request()->all();
305
306
        foreach ($rules as $a => $b) {
307
            if (is_int($a)) {
308
                $rules[$b] = 'required';
309
            } else {
310
                $rules[$a] = $b;
311
            }
312
        }
313
314
        $validator = Validator::make($input_arr, $rules, $messages);
315
        if ($validator->fails()) {
316
            $message = $validator->errors()->all();
317
            throw new CBValidationException(implode("; ",$message));
318
        }
319
    }
320
321
    public function pk($table)
322
    {
323
        return $this->findPrimaryKey($table);
324
    }
325
326
    public function findPrimaryKey($table)
327
    {
328
        $pk = DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
329
        if(!$pk) {
330
            return null;
331
        }
332
        return $pk->getColumns()[0];
333
    }
334
335
    public function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
336
    {
337
        $params = Request::all();
338
        $mainpath = trim(self::mainpath(), '/');
0 ignored issues
show
Bug introduced by
The method mainpath() does not exist on crocodicstudio\crudbooster\helpers\CB. ( Ignorable by Annotation )

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

338
        $mainpath = trim(self::/** @scrutinizer ignore-call */ mainpath(), '/');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
339
        $key = sanitizeXSS($key);
340
        $type = sanitizeXSS($type);
341
        $value = sanitizeXSS($value);
342
343
        if ($params['filter_column'] && $singleSorting) {
344
            foreach ($params['filter_column'] as $k => $filter) {
345
                foreach ($filter as $t => $val) {
346
                    if ($t == 'sorting') {
347
                        unset($params['filter_column'][$k]['sorting']);
348
                    }
349
                }
350
            }
351
        }
352
353
        $params['filter_column'][$key][$type] = $value;
354
355
        if (isset($params)) {
356
            return $mainpath.'?'.http_build_query($params);
357
        } else {
358
            return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
359
        }
360
    }
361
362
363
    public function getUrlParameters($exception = null)
364
    {
365
        $get = request()->all();
366
        $inputhtml = '';
367
368
        if ($get) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $get 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...
369
            if (is_array($exception)) {
370
                foreach ($exception as $e) {
371
                    unset($get[$e]);
372
                }
373
            }
374
            $string_parameters = http_build_query($get);
375
            $string_parameters_array = explode('&', $string_parameters);
376
            foreach ($string_parameters_array as $s) {
377
                $part = explode('=', $s);
378
                if(isset($part[0]) && isset($part[1])) {
379
                    $name = htmlspecialchars(urldecode($part[0]));
380
                    $name = strip_tags($name);
381
                    $value = htmlspecialchars(urldecode($part[1]));
382
                    $value = strip_tags($value);
383
                    if ($name) {
384
                        $inputhtml .= "<input type='hidden' name='$name' value='$value'/>\n";
385
                    }
386
                }
387
            }
388
        }
389
390
        return $inputhtml;
391
    }
392
393
394
    public function routeGet($prefix, $controller) {
395
        $alias = str_replace("@"," ", $controller);
396
        $alias = ucwords($alias);
397
        $alias = str_replace(" ","",$alias);
398
        Route::get($prefix, ['uses' => $controller, 'as' => $alias]);
399
    }
400
401
    public function routePost($prefix, $controller) {
402
        $alias = str_replace("@"," ", $controller);
403
        $alias = ucwords($alias);
404
        $alias = str_replace(" ","",$alias);
405
        Route::post($prefix, ['uses' => $controller, 'as' => $alias]);
406
    }
407
408
    public function routeGroupBackend(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
409
        Route::group([
410
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBBackend::class],
411
            'prefix' => cbConfig('ADMIN_PATH'),
412
            'namespace' => $namespace,
413
        ], $callback);
414
    }
415
416
    /*
417
    | --------------------------------------------------------------------------------------------------------------
418
    | Alternate route for Laravel Route::controller
419
    | --------------------------------------------------------------------------------------------------------------
420
    | $prefix       = path of route
421
    | $controller   = controller name
422
    |
423
    */
424
    public function routeController($prefix, $controller)
425
    {
426
427
        $prefix = trim($prefix, '/').'/';
428
429
        if(substr($controller,0,1) != "\\") {
430
            $controller = "\App\Http\Controllers\\".$controller;
431
        }
432
433
        $exp = explode("\\", $controller);
434
        $controller_name = end($exp);
435
436
        try {
437
            Route::get($prefix, ['uses' => $controller.'@getIndex', 'as' => $controller_name.'GetIndex']);
438
439
            $controller_class = new \ReflectionClass($controller);
440
            $controller_methods = $controller_class->getMethods(\ReflectionMethod::IS_PUBLIC);
441
            $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';
442
            foreach ($controller_methods as $method) {
443
444
                if ($method->class != 'Illuminate\Routing\Controller' && $method->name != 'getIndex') {
445
                    if (substr($method->name, 0, 3) == 'get') {
446
                        $method_name = substr($method->name, 3);
447
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
0 ignored issues
show
Bug introduced by
It seems like preg_split('/(?=[A-Z])/', $method_name) can also be of type false; however, parameter $input of array_filter() does only seem to accept array, 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

447
                        $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
448
                        $slug = strtolower(implode('-', $slug));
449
                        $slug = ($slug == 'index') ? '' : $slug;
450
                        Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller_name.'Get'.$method_name]);
451
                    } elseif (substr($method->name, 0, 4) == 'post') {
452
                        $method_name = substr($method->name, 4);
453
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
454
                        Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
455
                            'uses' => $controller.'@'.$method->name,
456
                            'as' => $controller_name.'Post'.$method_name,
457
                        ]);
458
                    }
459
                }
460
            }
461
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
462
463
        }
464
    }
465
}
466