Passed
Push — master ( f5f59c...7a263d )
by Ferry
04:39
created

CB::routeGroupDeveloper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
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
            $first = DB::table($table);
236
            foreach ($id as $k => $v) {
237
                $first->where($k, $v);
238
            }
239
240
            return $first->first();
241
        } else {
242
            $pk = $this->pk($table);
243
244
            return DB::table($table)->where($pk, $id)->first();
245
        }
246
    }
247
248
    public function listAllTable()
249
    {
250
        return DB::connection()->getDoctrineSchemaManager()->listTableNames();
251
    }
252
253
    public function listAllColumns($table)
254
    {
255
        return Schema::getColumnListing($table);
256
    }
257
258
    public function findAll($table, $condition_array = [])
259
    {
260
        return DB::table($table)->where($condition_array)->get();
261
    }
262
263
    public function redirectBack($message, $type = 'warning')
264
    {
265
        if (request()->ajax()) {
266
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $_SERVER['HTTP_REFERER']]);
267
        } else {
268
            return redirect()->back()->withInput()
269
                ->with(['message'=> $message, 'message_type'=> $type]);
270
        }
271
    }
272
273
    public function redirect($to, $message, $type = 'warning')
274
    {
275
        if (Request::ajax()) {
276
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]);
277
        } else {
278
            return redirect($to)->with(['message' => $message, 'message_type' => $type]);
279
        }
280
    }
281
282
283
    public function getCurrentMethod()
284
    {
285
        $action = str_replace("App\Http\Controllers", "", Route::currentRouteAction());
286
        $atloc = strpos($action, '@') + 1;
287
        $method = substr($action, $atloc);
288
289
        return $method;
290
    }
291
292
    public function stringBetween($string, $start, $end)
293
    {
294
        $string = ' '.$string;
295
        $ini = strpos($string, $start);
296
        if ($ini == 0) {
297
            return '';
298
        }
299
        $ini += strlen($start);
300
        $len = strpos($string, $end, $ini) - $ini;
301
302
        return substr($string, $ini, $len);
303
    }
304
305
    /**
306
     * @param array $rules
307
     * @param array $messages
308
     * @throws CBValidationException
309
     */
310
    public function validation($rules = [], $messages = [])
311
    {
312
        $input_arr = request()->all();
313
314
        foreach ($rules as $a => $b) {
315
            if (is_int($a)) {
316
                $rules[$b] = 'required';
317
            } else {
318
                $rules[$a] = $b;
319
            }
320
        }
321
322
        $validator = Validator::make($input_arr, $rules, $messages);
323
        if ($validator->fails()) {
324
            $message = $validator->errors()->all();
325
            throw new CBValidationException(implode("; ",$message));
326
        }
327
    }
328
329
    public function pk($table)
330
    {
331
        return $this->findPrimaryKey($table);
332
    }
333
334
    public function findPrimaryKey($table)
335
    {
336
        $pk = DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
337
        if(!$pk) {
338
            return null;
339
        }
340
        return $pk->getColumns()[0];
341
    }
342
343
    public function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
344
    {
345
        $params = Request::all();
346
        $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

346
        $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...
347
        $key = sanitizeXSS($key);
348
        $type = sanitizeXSS($type);
349
        $value = sanitizeXSS($value);
350
351
        if ($params['filter_column'] && $singleSorting) {
352
            foreach ($params['filter_column'] as $k => $filter) {
353
                foreach ($filter as $t => $val) {
354
                    if ($t == 'sorting') {
355
                        unset($params['filter_column'][$k]['sorting']);
356
                    }
357
                }
358
            }
359
        }
360
361
        $params['filter_column'][$key][$type] = $value;
362
363
        if (isset($params)) {
364
            return $mainpath.'?'.http_build_query($params);
365
        } else {
366
            return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
367
        }
368
    }
369
370
371
    public function getUrlParameters($exception = null)
372
    {
373
        $get = request()->all();
374
        $inputhtml = '';
375
376
        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...
377
            if (is_array($exception)) {
378
                foreach ($exception as $e) {
379
                    unset($get[$e]);
380
                }
381
            }
382
            $string_parameters = http_build_query($get);
383
            $string_parameters_array = explode('&', $string_parameters);
384
            foreach ($string_parameters_array as $s) {
385
                $part = explode('=', $s);
386
                if(isset($part[0]) && isset($part[1])) {
387
                    $name = htmlspecialchars(urldecode($part[0]));
388
                    $name = strip_tags($name);
389
                    $value = htmlspecialchars(urldecode($part[1]));
390
                    $value = strip_tags($value);
391
                    if ($name) {
392
                        $inputhtml .= "<input type='hidden' name='$name' value='$value'/>\n";
393
                    }
394
                }
395
            }
396
        }
397
398
        return $inputhtml;
399
    }
400
401
402
    public function routeGet($prefix, $controller) {
403
        $alias = str_replace("@"," ", $controller);
404
        $alias = ucwords($alias);
405
        $alias = str_replace(" ","",$alias);
406
        Route::get($prefix, ['uses' => $controller, 'as' => $alias]);
407
    }
408
409
    public function routePost($prefix, $controller) {
410
        $alias = str_replace("@"," ", $controller);
411
        $alias = ucwords($alias);
412
        $alias = str_replace(" ","",$alias);
413
        Route::post($prefix, ['uses' => $controller, 'as' => $alias]);
414
    }
415
416
    public function routeGroupBackend(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
417
        Route::group([
418
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBBackend::class],
419
            'prefix' => cb()->getAdminPath(),
420
            'namespace' => $namespace,
421
        ], $callback);
422
    }
423
424
    public function routeGroupDeveloper(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
425
        Route::group([
426
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBDeveloper::class],
427
            'prefix' => "developer/".getSetting('developer_path'),
428
            'namespace' => $namespace,
429
        ], $callback);
430
    }
431
432
    /*
433
    | --------------------------------------------------------------------------------------------------------------
434
    | Alternate route for Laravel Route::controller
435
    | --------------------------------------------------------------------------------------------------------------
436
    | $prefix       = path of route
437
    | $controller   = controller name
438
    |
439
    */
440
    public function routeController($prefix, $controller)
441
    {
442
443
        $prefix = trim($prefix, '/').'/';
444
445
        if(substr($controller,0,1) != "\\") {
446
            $controller = "\App\Http\Controllers\\".$controller;
447
        }
448
449
        $exp = explode("\\", $controller);
450
        $controller_name = end($exp);
451
452
        try {
453
            Route::get($prefix, ['uses' => $controller.'@getIndex', 'as' => $controller_name.'GetIndex']);
454
455
            $controller_class = new \ReflectionClass($controller);
456
            $controller_methods = $controller_class->getMethods(\ReflectionMethod::IS_PUBLIC);
457
            $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';
458
            foreach ($controller_methods as $method) {
459
460
                if ($method->class != 'Illuminate\Routing\Controller' && $method->name != 'getIndex') {
461
                    if (substr($method->name, 0, 3) == 'get') {
462
                        $method_name = substr($method->name, 3);
463
                        $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

463
                        $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
464
                        $slug = strtolower(implode('-', $slug));
465
                        $slug = ($slug == 'index') ? '' : $slug;
466
                        Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller_name.'Get'.$method_name]);
467
                    } elseif (substr($method->name, 0, 4) == 'post') {
468
                        $method_name = substr($method->name, 4);
469
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
470
                        Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
471
                            'uses' => $controller.'@'.$method->name,
472
                            'as' => $controller_name.'Post'.$method_name,
473
                        ]);
474
                    }
475
                }
476
            }
477
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
478
479
        }
480
    }
481
}
482