Passed
Push — master ( ab23d3...456c2a )
by Ferry
05:06
created

CB::findAll()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 22
c 0
b 0
f 0
nc 11
nop 2
dl 0
loc 33
rs 8.0555
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 htmlHelper() {
23
        return (new HTMLHelper());
24
    }
25
26
    public function getRoleByName($roleName) {
27
        return $this->find("cb_roles",['name'=>$roleName]);
28
    }
29
30
    public function fcm() {
31
        return new FCM();
32
    }
33
34
    public function sidebar() {
35
        return new SidebarMenus();
36
    }
37
38
    public function session() {
39
        return new UserSession();
40
    }
41
42
    public function getDeveloperUrl($path = null) {
43
        $path = ($path)?"/".trim($path,"/"):null;
44
        return url("developer/".getSetting("developer_path")).$path;
45
    }
46
47
    public function getProfileUrl() {
48
        return $this->getAdminUrl()."/profile";
49
    }
50
51
    public function getLogoutUrl() {
52
        return $this->getAdminUrl()."/logout";
53
    }
54
55
    public function getLoginUrl() {
56
        return $this->getAdminUrl("login");
57
    }
58
59
    public function getAdminPath() {
60
        return getSetting("ADMIN_PATH","admin");
61
    }
62
63
    public function getAdminUrl($path = null) {
64
        $path = ($path)?"/".trim($path,"/"):null;
65
        return url($this->getAdminPath()).$path;
0 ignored issues
show
Bug introduced by
Are you sure url($this->getAdminPath()) 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

65
        return /** @scrutinizer ignore-type */ url($this->getAdminPath()).$path;
Loading history...
66
    }
67
68
    public function getAppName() {
69
        return getSetting("APP_NAME", env("APP_NAME","CRUDBOOSTER"));
70
    }
71
72
    /**
73
     * @param $filename
74
     * @param $extension
75
     * @param $file
76
     * @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...
77
     * @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...
78
     * @return string
79
     * @throws \Exception
80
     */
81
    private function uploadFileProcess($filename, $extension, $file, $encrypt = true, $resize_width = null, $resize_height = null)
82
    {
83
        if(in_array($extension,cbConfig("UPLOAD_FILE_EXTENSION_ALLOWED"))) {
84
            $file_path = cbConfig("UPLOAD_PATH_FORMAT");
85
            $file_path = str_replace("{Y}",date('Y'), $file_path);
86
            $file_path = str_replace("{m}", date('m'), $file_path);
87
            $file_path = str_replace("{d}", date("d"), $file_path);
88
89
            //Create Directory Base On Template
90
            Storage::makeDirectory($file_path);
91
            Storage::put($file_path."/index.html","&nbsp;","public");
92
            Storage::put($file_path."/.gitignore","!.gitignore","public");
93
94
            if ($encrypt == true) {
95
                $filename = md5(strRandom(5)).'.'.$extension;
96
            } else {
97
                $filename = slug($filename, '_').'.'.$extension;
98
            }
99
100
            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...
101
                $this->resizeImage($file, $file_path.'/'.$filename, $resize_width, $resize_height);
102
                return $file_path.'/'.$filename;
103
            }else{
104
                if (Storage::putFileAs($file_path, $file, $filename, 'public')) {
105
                    return $file_path.'/'.$filename;
106
                } else {
107
                    throw new \Exception("Something went wrong, file can't upload!");
108
                }
109
            }
110
        }else{
111
            throw new \Exception("The file format is not allowed!");
112
        }
113
    }
114
115
    /**
116
     * @param $base64_value
117
     * @param bool $encrypt
118
     * @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...
119
     * @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...
120
     * @throws \Exception
121
     */
122
    public function uploadBase64($filename, $base64_value, $encrypt = true, $resize_width = null, $resize_height = null)
123
    {
124
        $fileData = base64_decode($base64_value);
125
        $mime_type = finfo_buffer(finfo_open(), $fileData, FILEINFO_MIME_TYPE);
126
        if($mime_type) {
127
            if($mime_type = explode('/', $mime_type)) {
128
                $ext = $mime_type[1];
129
                if($filename && $ext) {
130
                    return $this->uploadFileProcess($filename, $ext, $fileData, $encrypt, $resize_width, $resize_height);
131
                }
132
            }else {
133
                throw new \Exception("Mime type not found");
134
            }
135
        }else{
136
            throw new \Exception("Mime type not found");
137
        }
138
    }
139
140
    /**
141
     * @param $name
142
     * @param bool $encrypt
143
     * @param int $resize_width
144
     * @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...
145
     * @return string
146
     * @throws \Exception
147
     */
148
    public function uploadFile($name, $encrypt = true, $resize_width = null, $resize_height = null)
149
    {
150
        if (request()->hasFile($name)) {
151
            $file = request()->file($name);
152
            $filename = $file->getClientOriginalName();
153
            $ext = strtolower($file->getClientOriginalExtension());
154
155
            if($filename && $ext) {
156
                return $this->uploadFileProcess($filename, $ext, $file, $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

156
                return $this->uploadFileProcess($filename, $ext, $file, $encrypt, /** @scrutinizer ignore-type */ $resize_width, $resize_height);
Loading history...
157
            }
158
159
        } else {
160
            throw new \Exception("There is no file send to server!");
161
        }
162
    }
163
164
    /**
165
     * @param $file
166
     * @param $fullFilePath
167
     * @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...
168
     * @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...
169
     * @param int $qty
170
     * @param int $thumbQty
171
     * @throws \Exception
172
     */
173
    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

173
    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...
174
    {
175
        $images_ext = cbConfig("UPLOAD_IMAGE_EXTENSION_ALLOWED");
176
177
        $filename = basename($fullFilePath);
178
        $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...
179
        $ext = pathinfo($fullFilePath, PATHINFO_EXTENSION);
180
181
        if (in_array(strtolower($ext), $images_ext)) {
182
183
            // Upload file
184
            $img = Image::make($file);
185
            $img->encode($ext, $qty);
186
187
            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...
188
                $img->fit($resize_width, $resize_height);
189
190
            } 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...
191
192
                $img->resize($resize_width, null, function ($constraint) {
193
                    $constraint->aspectRatio();
194
                });
195
196
            } 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...
introduced by
$resize_height is of type null, thus it always evaluated to false.
Loading history...
197
198
                $img->resize(null, $resize_height, function ($constraint) {
199
                    $constraint->aspectRatio();
200
                });
201
202
            } else {
203
204
                if ($img->width() > cbConfig("DEFAULT_IMAGE_MAX_WIDTH_RES")) {
205
                    $img->resize(cbConfig("DEFAULT_IMAGE_MAX_WIDTH_RES"), null, function ($constraint) {
206
                        $constraint->aspectRatio();
207
                    });
208
                }
209
            }
210
211
            Storage::put($fullFilePath, $img, 'public');
212
        }else{
213
            throw new \Exception("The file format is not allowed!");
214
        }
215
    }
216
217
    public function update($table, $id, $data)
218
    {
219
        DB::table($table)
220
            ->where($this->pk($table), $id)
221
            ->update($data);
222
    }
223
224
    public function updateCompact($table, $id, $params) {
225
        $data = [];
226
        foreach ($params as $param) {
227
            $data[$param] = request($param);
228
        }
229
        $this->update($table, $id, $data);
230
    }
231
232
    public function find($table, $id)
233
    {
234
        if (is_array($id)) {
235
            $idHash = md5("find".$table.serialize($id));
236
            if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
237
238
            $first = DB::table($table);
239
            foreach ($id as $k => $v) {
240
                $first->where($k, $v);
241
            }
242
243
            $data = $first->first();
244
            miscellanousSingleton()->setData($idHash,$data);
245
            return $data;
246
        } else {
247
            $idHash = md5("find".$table.$id);
248
            if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
249
250
            $pk = $this->pk($table);
251
            $data = DB::table($table)->where($pk, $id)->first();
252
            miscellanousSingleton()->setData($idHash,$data);
253
            return $data;
254
        }
255
    }
256
257
    /**
258
     * @param $table
259
     * @param callable|string|null $conditionOrCallback
260
     * @return \Illuminate\Support\Collection|mixed
261
     */
262
    public function findAll($table, $conditionOrCallback = null)
263
    {
264
        $data = [];
265
        $idHash = null;
266
267
        if(is_array($conditionOrCallback)) {
268
            $idHash = md5("findAll".$table.serialize($conditionOrCallback));
269
            if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
270
271
            $data = DB::table($table)->where($conditionOrCallback)->get();
272
        } elseif (is_callable($conditionOrCallback)) {
273
            $idHash = "findAll".$table.spl_object_hash($conditionOrCallback);
0 ignored issues
show
Bug introduced by
It seems like $conditionOrCallback can also be of type callable and string; however, parameter $obj of spl_object_hash() does only seem to accept object, 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

273
            $idHash = "findAll".$table.spl_object_hash(/** @scrutinizer ignore-type */ $conditionOrCallback);
Loading history...
274
            if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
275
276
            $data = DB::table($table);
277
            $data = call_user_func($conditionOrCallback, $data);
278
            $data = $data->get();
279
        } else {
280
            $idHash = md5("findAll".$table.$conditionOrCallback);
0 ignored issues
show
Bug introduced by
Are you sure $conditionOrCallback of type callable|null|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

280
            $idHash = md5("findAll".$table./** @scrutinizer ignore-type */ $conditionOrCallback);
Loading history...
281
            if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
282
283
            $data = DB::table($table);
284
            if($conditionOrCallback) {
285
                $data = $data->whereRaw($conditionOrCallback);
0 ignored issues
show
Bug introduced by
It seems like $conditionOrCallback can also be of type callable; however, parameter $sql of Illuminate\Database\Query\Builder::whereRaw() 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

285
                $data = $data->whereRaw(/** @scrutinizer ignore-type */ $conditionOrCallback);
Loading history...
286
            }
287
            $data = $data->get();
288
        }
289
290
        if($idHash && $data) {
291
            miscellanousSingleton()->setData($idHash, $data);
292
        }
293
294
        return $data;
295
    }
296
297
    public function listAllTable()
298
    {
299
        $idHash = md5("listAllTable");
300
        if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
301
        $data = DB::connection()->getDoctrineSchemaManager()->listTableNames();
302
        miscellanousSingleton()->setData($idHash, $data);
303
        return $data;
304
    }
305
306
    public function listAllColumns($table)
307
    {
308
        $idHash = md5("listAllColumns".$table);
309
        if(miscellanousSingleton()->hasData($idHash)) return miscellanousSingleton()->getData($idHash);
310
        $data = Schema::getColumnListing($table);
311
        miscellanousSingleton()->setData($idHash, $data);
312
        return $data;
313
    }
314
315
    public function redirectBack($message, $type = 'warning')
316
    {
317
        if (request()->ajax()) {
318
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $_SERVER['HTTP_REFERER']]);
319
        } else {
320
            return redirect()->back()->withInput()
321
                ->with(['message'=> $message, 'message_type'=> $type]);
322
        }
323
    }
324
325
    public function redirect($to, $message, $type = 'warning')
326
    {
327
        if (Request::ajax()) {
328
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]);
329
        } else {
330
            return redirect($to)->with(['message' => $message, 'message_type' => $type]);
331
        }
332
    }
333
334
335
    public function getCurrentMethod()
336
    {
337
        $action = str_replace("App\Http\Controllers", "", Route::currentRouteAction());
338
        $atloc = strpos($action, '@') + 1;
339
        $method = substr($action, $atloc);
340
341
        return $method;
342
    }
343
344
    public function stringBetween($string, $start, $end)
345
    {
346
        $string = ' '.$string;
347
        $ini = strpos($string, $start);
348
        if ($ini == 0) {
349
            return '';
350
        }
351
        $ini += strlen($start);
352
        $len = strpos($string, $end, $ini) - $ini;
353
354
        return substr($string, $ini, $len);
355
    }
356
357
    /**
358
     * @param array $rules
359
     * @param array $messages
360
     * @throws CBValidationException
361
     */
362
    public function validation($rules = [], $messages = [])
363
    {
364
        $input_arr = request()->all();
365
366
        foreach ($rules as $a => $b) {
367
            if (is_int($a)) {
368
                $rules[$b] = 'required';
369
            } else {
370
                $rules[$a] = $b;
371
            }
372
        }
373
374
        $validator = Validator::make($input_arr, $rules, $messages);
375
        if ($validator->fails()) {
376
            $message = $validator->errors()->all();
377
            throw new CBValidationException(implode("; ",$message));
378
        }
379
    }
380
381
    public function pk($table)
382
    {
383
        return $this->findPrimaryKey($table);
384
    }
385
386
    public function findPrimaryKey($table)
387
    {
388
        $pk = DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
389
        if(!$pk) {
390
            return null;
391
        }
392
        return $pk->getColumns()[0];
393
    }
394
395
    public function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
396
    {
397
        $params = Request::all();
398
        $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

398
        $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...
399
        $key = sanitizeXSS($key);
400
        $type = sanitizeXSS($type);
401
        $value = sanitizeXSS($value);
402
403
        if ($params['filter_column'] && $singleSorting) {
404
            foreach ($params['filter_column'] as $k => $filter) {
405
                foreach ($filter as $t => $val) {
406
                    if ($t == 'sorting') {
407
                        unset($params['filter_column'][$k]['sorting']);
408
                    }
409
                }
410
            }
411
        }
412
413
        $params['filter_column'][$key][$type] = $value;
414
415
        if (isset($params)) {
416
            return $mainpath.'?'.http_build_query($params);
417
        } else {
418
            return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
419
        }
420
    }
421
422
423
    public function getUrlParameters($exception = null)
424
    {
425
        $get = request()->all();
426
        $inputhtml = '';
427
428
        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...
429
            if (is_array($exception)) {
430
                foreach ($exception as $e) {
431
                    unset($get[$e]);
432
                }
433
            }
434
            $string_parameters = http_build_query($get);
435
            $string_parameters_array = explode('&', $string_parameters);
436
            foreach ($string_parameters_array as $s) {
437
                $part = explode('=', $s);
438
                if(isset($part[0]) && isset($part[1])) {
439
                    $name = htmlspecialchars(urldecode($part[0]));
440
                    $name = strip_tags($name);
441
                    $value = htmlspecialchars(urldecode($part[1]));
442
                    $value = strip_tags($value);
443
                    if ($name) {
444
                        $inputhtml .= "<input type='hidden' name='$name' value='$value'/>\n";
445
                    }
446
                }
447
            }
448
        }
449
450
        return $inputhtml;
451
    }
452
453
454
    public function routeGet($prefix, $controller) {
455
        $alias = str_replace("@"," ", $controller);
456
        $alias = ucwords($alias);
457
        $alias = str_replace(" ","",$alias);
458
        Route::get($prefix, ['uses' => $controller, 'as' => $alias]);
459
    }
460
461
    public function routePost($prefix, $controller) {
462
        $alias = str_replace("@"," ", $controller);
463
        $alias = ucwords($alias);
464
        $alias = str_replace(" ","",$alias);
465
        Route::post($prefix, ['uses' => $controller, 'as' => $alias]);
466
    }
467
468
    public function routeGroupBackend(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
469
        Route::group([
470
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBBackend::class],
471
            'prefix' => cb()->getAdminPath(),
472
            'namespace' => $namespace,
473
        ], $callback);
474
    }
475
476
    public function routeGroupDeveloper(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
477
        Route::group([
478
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBDeveloper::class],
479
            'prefix' => "developer/".getSetting('developer_path'),
480
            'namespace' => $namespace,
481
        ], $callback);
482
    }
483
484
    /*
485
    | --------------------------------------------------------------------------------------------------------------
486
    | Alternate route for Laravel Route::controller
487
    | --------------------------------------------------------------------------------------------------------------
488
    | $prefix       = path of route
489
    | $controller   = controller name
490
    |
491
    */
492
    public function routeController($prefix, $controller)
493
    {
494
495
        $prefix = trim($prefix, '/').'/';
496
497
        if(substr($controller,0,1) != "\\") {
498
            $controller = "\App\Http\Controllers\\".$controller;
499
        }
500
501
        $exp = explode("\\", $controller);
502
        $controller_name = end($exp);
503
504
        try {
505
            Route::get($prefix, ['uses' => $controller.'@getIndex', 'as' => $controller_name.'GetIndex']);
506
507
            $controller_class = new \ReflectionClass($controller);
508
            $controller_methods = $controller_class->getMethods(\ReflectionMethod::IS_PUBLIC);
509
            $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';
510
            foreach ($controller_methods as $method) {
511
512
                if ($method->class != 'Illuminate\Routing\Controller' && $method->name != 'getIndex') {
513
                    if (substr($method->name, 0, 3) == 'get') {
514
                        $method_name = substr($method->name, 3);
515
                        $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

515
                        $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
516
                        $slug = strtolower(implode('-', $slug));
517
                        $slug = ($slug == 'index') ? '' : $slug;
518
                        Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller_name.'Get'.$method_name]);
519
                    } elseif (substr($method->name, 0, 4) == 'post') {
520
                        $method_name = substr($method->name, 4);
521
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
522
                        Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
523
                            'uses' => $controller.'@'.$method->name,
524
                            'as' => $controller_name.'Post'.$method_name,
525
                        ]);
526
                    }
527
                }
528
            }
529
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
530
531
        }
532
    }
533
}
534