Passed
Push — master ( c52d76...a99d60 )
by Iman
09:00 queued 04:52
created

CRUDBooster::canCRUD()   B

Complexity

Conditions 9
Paths 5

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
nc 5
nop 0
dl 0
loc 16
c 0
b 0
f 0
cc 9
rs 7.756

2 Methods

Rating   Name   Duplication   Size   Complexity  
A CRUDBooster::getValueFilter() 0 5 2
A CRUDBooster::isColumnNULL() 0 3 1
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use crocodicstudio\crudbooster\CBCoreModule\CbUsersRepo;
6
use crocodicstudio\crudbooster\helpers\Cache as LaravelCache;
7
use crocodicstudio\crudbooster\Modules\LogsModule\LogsRepository;
8
use crocodicstudio\crudbooster\Modules\PrivilegeModule\PrivilegeHelpers;
9
use Session;
10
use Request;
11
use Schema;
12
use Cache;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, crocodicstudio\crudbooster\helpers\Cache. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use DB;
14
use Route;
15
use Config;
16
use Validator;
17
18
class CRUDBooster
19
{
20
    use PrivilegeHelpers;
0 ignored issues
show
introduced by
The trait crocodicstudio\crudboost...Module\PrivilegeHelpers requires some properties which are not provided by crocodicstudio\crudbooster\helpers\CRUDBooster: $path, $is_read, $is_visible, $is_delete, $is_create, $is_edit
Loading history...
21
22
    public static function get($table, $string_conditions = null, $orderby = null, $limit = null, $skip = null)
23
    {
24
        $table = self::parseSqlTable($table);
25
        $table = $table['table'];
26
        $query = DB::table($table);
27
        if ($string_conditions) {
28
            $query->whereraw($string_conditions);
29
        }
30
        if ($orderby) {
31
            $query->orderbyraw($orderby);
32
        }
33
        if ($limit) {
34
            $query->take($limit);
35
        }
36
        if ($skip) {
37
            $query->skip($skip);
38
        }
39
40
        return $query->get();
41
    }
42
43
    public static function parseSqlTable($table)
44
    {
45
        $f = explode('.', $table);
46
47
        if (count($f) == 1) {
48
            return ["table" => $f[0], "database" => cbConfig('MAIN_DB_DATABASE')];
49
        }
50
        if (count($f) == 2) {
51
            return ["database" => $f[0], "table" => $f[1]];
52
        }
53
54
        if (count($f) == 3) {
55
            return ["table" => $f[0], "schema" => $f[1], "table" => $f[2]];
56
        }
57
58
        return false;
59
    }
60
61
    public static function me()
62
    {
63
        return CbUsersRepo::find(session('admin_id'));
64
    }
65
66
    public static function myName()
67
    {
68
        return session('admin_name');
69
    }
70
71
    public static function myPhoto()
72
    {
73
        return session('admin_photo');
74
    }
75
76
    public static function isLocked()
77
    {
78
        return session('admin_lock');
79
    }
80
81
    public static function getCurrentModule()
82
    {
83
        return GetCurrentX::getCurrentModule();
84
    }
85
86
    public static function getCurrentDashboardId()
87
    {
88
        return GetCurrentX::getCurrentDashboardId();
89
    }
90
91
    public static function getCurrentMenuId()
92
    {
93
        return GetCurrentX::getCurrentMenuId();
94
    }
95
96
    public static function adminPath($path = null)
97
    {
98
        return url(cbAdminPath().'/'.$path);
99
    }
100
101
    public static function deleteConfirm($redirectTo)
102
    {
103
        echo 'swal({   
104
				title: "'.cbTrans('delete_title_confirm').'",   
0 ignored issues
show
Bug introduced by
Are you sure cbTrans('delete_title_confirm') of type null|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

104
				title: "'./** @scrutinizer ignore-type */ cbTrans('delete_title_confirm').'",   
Loading history...
105
				text: "'.cbTrans('delete_description_confirm').'",   
0 ignored issues
show
Bug introduced by
Are you sure cbTrans('delete_description_confirm') of type null|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

105
				text: "'./** @scrutinizer ignore-type */ cbTrans('delete_description_confirm').'",   
Loading history...
106
				type: "warning",   
107
				showCancelButton: true,   
108
				confirmButtonColor: "#ff0000",   
109
				confirmButtonText: "'.cbTrans('confirmation_yes').'",  
0 ignored issues
show
Bug introduced by
Are you sure cbTrans('confirmation_yes') of type null|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

109
				confirmButtonText: "'./** @scrutinizer ignore-type */ cbTrans('confirmation_yes').'",  
Loading history...
110
				cancelButtonText: "'.cbTrans('confirmation_no').'",  
0 ignored issues
show
Bug introduced by
Are you sure cbTrans('confirmation_no') of type null|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

110
				cancelButtonText: "'./** @scrutinizer ignore-type */ cbTrans('confirmation_no').'",  
Loading history...
111
				closeOnConfirm: false }, 
112
				function(){  location.href="'.$redirectTo.'" });';
113
    }
114
115
    public static function getCurrentId()
116
    {
117
        return GetCurrentX::getCurrentId();
118
    }
119
120
    public static function getCurrentMethod()
121
    {
122
        return GetCurrentX::getCurrentMethod();
123
    }
124
125
    public static function clearCache($name)
126
    {
127
        return Cache::forget($name);
128
    }
129
130
    public static function isColumnNULL($table, $field)
131
    {
132
        return DbInspector::isColNull($table, $field);
133
    }
134
135
    public static function getValueFilter($field)
136
    {
137
        $filter = request('filter_column');
138
        if ($filter[$field]) {
139
            return $filter[$field]['value'];
140
        }
141
    }
142
143
    private static function getFilter($field, $index)
144
    {
145
        $filter = request('filter_column');
146
        if ($filter[$field]) {
147
            return $filter[$field][$index];
148
        }
149
    }
150
151
    public static function getSortingFilter($field)
152
    {
153
        return self::getFilter($field, 'sorting');
154
    }
155
156
    public static function getTypeFilter($field)
157
    {
158
        return self::getFilter($field, 'type');
159
    }
160
161
    public static function stringBetween($string, $start, $end)
162
    {
163
        $string = ' '.$string;
164
        $ini = strpos($string, $start);
165
        if ($ini == 0) {
166
            return '';
167
        }
168
        $ini += strlen($start);
169
        $len = strpos($string, $end, $ini) - $ini;
170
171
        return substr($string, $ini, $len);
172
    }
173
174
    public static function first($table, $id)
175
    {
176
        $table = self::parseSqlTable($table)['table'];
177
        if (! is_array($id)) {
178
            $pk = self::pk($table);
179
180
            return DB::table($table)->where($pk, $id)->first();
181
        }
182
183
        $first = DB::table($table);
184
        foreach ($id as $k => $v) {
185
            $first->where($k, $v);
186
        }
187
188
        return $first->first();
189
    }
190
191
    public static function pk($table)
192
    {
193
        return self::findPrimaryKey($table);
194
    }
195
196
    public static function findPrimaryKey($table)
197
    {
198
        return DbInspector::findPK($table);
199
    }
200
201
    public static function getCache($section, $cacheName)
202
    {
203
        return LaravelCache::get($section, $cacheName);
204
    }
205
206
    public static function putCache($section, $cacheName, $cacheValue)
207
    {
208
        return LaravelCache::put($section, $cacheName, $cacheValue);
209
    }
210
211
    public static function valid($arr = [], $type = 'json')
212
    {
213
        $input_arr = request()->all();
214
215
        foreach ($arr as $a => $b) {
216
            if (is_int($a)) {
217
                $arr[$b] = 'required';
218
            } else {
219
                $arr[$a] = $b;
220
            }
221
        }
222
223
        $validator = Validator::make($input_arr, $arr);
224
225
        if (!$validator->fails()) {
226
            return true;
227
        }
228
        $message = $validator->errors()->all();
229
230
        if ($type == 'json') {
231
            $result = [];
232
            $result['api_status'] = 0;
233
            $result['api_message'] = implode(', ', $message);
234
            sendAndTerminate(response()->json($result, 200));
0 ignored issues
show
Bug introduced by
The method json() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

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

234
            sendAndTerminate(response()->/** @scrutinizer ignore-call */ json($result, 200));
Loading history...
235
        }
236
237
        $res = redirect()->back()->with(['message' => implode('<br/>', $message), 'message_type' => 'warning'])->withInput();
238
        sendAndTerminate($res);
239
    }
240
241
    public static function flushCache()
242
    {
243
        Cache::flush();
244
    }
245
246
    public static function forgetCache($section, $cacheName)
247
    {
248
        return LaravelCache::forgetCache($section, $cacheName);
249
    }
250
251
    public static function getForeignKey($parent_table, $child_table)
252
    {
253
        $parent_table = CRUDBooster::parseSqlTable($parent_table)['table'];
254
        $child_table = CRUDBooster::parseSqlTable($child_table)['table'];
255
256
        if (\Schema::hasColumn($child_table, 'id_'.$parent_table)) {
257
            return 'id_'.$parent_table;
258
        }
259
        return $parent_table.'_id';
260
    }
261
262
    public static function getTableForeignKey($fieldName)
263
    {
264
        if (substr($fieldName, 0, 3) == 'id_' || substr($fieldName, -3) == '_id') {
265
            return str_replace(['_id', 'id_'], '', $fieldName);
266
        }
267
    }
268
269
    public static function isForeignKey($fieldName)
270
    {
271
        return DbInspector::isForeignKeey($fieldName);
272
    }
273
274
    public static function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
275
    {
276
        $params = request()->all();
277
        $mainpath = trim(self::mainpath(), '/');
278
279
        if ($params['filter_column'] && $singleSorting) {
280
            foreach ($params['filter_column'] as $k => $filter) {
281
                foreach ($filter as $t => $val) {
282
                    if ($t == 'sorting') {
283
                        unset($params['filter_column'][$k]['sorting']);
284
                    }
285
                }
286
            }
287
        }
288
289
        $params['filter_column'][$key][$type] = $value;
290
291
        if (isset($params)) {
292
            return $mainpath.'?'.http_build_query($params);
293
        }
294
        return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
295
296
    }
297
298
    public static function mainpath($path = null)
299
    {
300
        $controllerName = strtok(Route::currentRouteAction(), '@');
301
        // $controllerName = array_pop(explode('\\', $controllerName));
302
        $controllerName = basename($controllerName);
303
        $route_url = route($controllerName.'GetIndex');
304
305
        if (! $path) {
306
            return trim($route_url, '/');
307
        }
308
309
        if (substr($path, 0, 1) == '?') {
310
            return trim($route_url, '/').$path;
311
        }
312
313
        return $route_url.'/'.$path;
314
    }
315
316
    public static function insertLog($description)
317
    {
318
        LogsRepository::insertLog('crudbooster: '.$description, self::myId());
319
    }
320
321
    public static function insertTryLog($action, $name = '')
322
    {
323
        self::insertLog(trans("logging.log_try_".$action, ['name' => $name, 'module' => self::getCurrentModule()]));
324
    }
325
326
    public static function myId()
327
    {
328
        return session('admin_id');
329
    }
330
331
    public static function referer()
332
    {
333
        return Request::server('HTTP_REFERER');
334
    }
335
336
    public static function listTables()
337
    {
338
        return DbInspector::listTables();
339
    }
340
341
    public static function listCbTables()
342
    {
343
        $tablesList = [];
344
        foreach (self::listTables() as $tableObj) {
345
346
            $tableName = $tableObj->TABLE_NAME;
347
            if ($tableName == config('database.migrations')) {
348
                continue;
349
            }
350
            if (substr($tableName, 0, 4) == 'cms_' && $tableName != 'cms_users') {
351
                continue;
352
            }
353
354
            $tablesList[] = $tableName;
355
        }
356
357
        return $tablesList;
358
    }
359
360
    public static function getUrlParameters($exception = null)
361
    {
362
        @$get = $_GET;
363
        $inputhtml = '';
364
365
        if (! $get) {
366
            return $inputhtml;
367
        }
368
        if (is_array($exception)) {
369
            foreach ($exception as $e) {
370
                unset($get[$e]);
371
            }
372
        }
373
374
        $string_parameters = http_build_query($get);
375
        foreach (explode('&', $string_parameters) as $s) {
376
            $part = explode('=', $s);
377
            $name = urldecode($part[0]);
378
            $value = urldecode($part[1]);
379
            $inputhtml .= "<input type='hidden' name='$name' value='$value'/>";
380
        }
381
382
        return $inputhtml;
383
    }
384
385
    public static function sendFCM($regID = [], $data)
386
    {
387
        return (new GoogleFCM)->send($regID, $data);
388
    }
389
390
    public static function isExistsController($table)
391
    {
392
        $ctrlName = ucwords(str_replace('_', ' ', $table));
393
        $ctrlName = str_replace(' ', '', $ctrlName).'Controller.php';
394
        $path = base_path(controllers_dir());
395
        $path2 = base_path(controllers_dir()."ControllerMaster/");
396
397
        if (file_exists($path.'Admin'.$ctrlName) || file_exists($path2.'Admin'.$ctrlName) || file_exists($path2.$ctrlName)) {
398
            return true;
399
        }
400
401
        return false;
402
    }
403
404
    public static function getTableColumns($table)
405
    {
406
        return DbInspector::getTableCols($table);
407
    }
408
409
    public static function getNameTable($columns)
410
    {
411
        return DbInspector::colName($columns);
412
    }
413
414
    public static function getFieldType($table, $field)
415
    {
416
        return DbInspector::getFieldTypes($table, $field);
417
    }
418
419
    public static function routeController($prefix, $controller, $namespace = null)
420
    {
421
        $prefix = trim($prefix, '/').'/';
422
423
        $namespace = ($namespace) ?: ctrlNamespace();
424
425
        try {
426
            Route::get($prefix, ['uses' => $controller.'@getIndex', 'as' => $controller.'GetIndex']);
427
428
            $controller_class = new \ReflectionClass($namespace.'\\'.$controller);
429
            $controller_methods = $controller_class->getMethods(\ReflectionMethod::IS_PUBLIC);
430
            $wildcards = '/{one?}/{two?}/{three?}/{four?}/{five?}';
431
            foreach ($controller_methods as $method) {
432
433
                if ($method->class == 'Illuminate\Routing\Controller' || $method->name == 'getIndex') {
434
                    continue;
435
                }
436
                if (substr($method->name, 0, 3) == 'get') {
437
                    $method_name = substr($method->name, 3);
438
                    $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

438
                    $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
439
                    $slug = strtolower(implode('-', $slug));
440
                    $slug = ($slug == 'index') ? '' : $slug;
441
                    Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller.'Get'.$method_name]);
442
                } elseif (substr($method->name, 0, 4) == 'post') {
443
                    $method_name = substr($method->name, 4);
444
                    $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
445
                    Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
446
                            'uses' => $controller.'@'.$method->name,
447
                            'as' => $controller.'Post'.$method_name,
448
                        ]);
449
                }
450
            }
451
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
452
453
        }
454
    }
455
456
    /*
457
    | -------------------------------------------------------------
458
    | Alternate route for Laravel Route::controller
459
    | -------------------------------------------------------------
460
    | $prefix       = path of route
461
    | $controller   = controller name
462
    | $namespace    = namespace of controller (optional)
463
    |
464
    */
465
466
    public static function denyAccess()
467
    {
468
        static::redirect(static::adminPath(), cbTrans('denied_access'));
469
    }
470
471
    public static function redirect($to, $message, $type = 'warning')
472
    {
473
        if (Request::ajax()) {
474
            sendAndTerminate(response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]));
475
        }
476
477
        sendAndTerminate(redirect($to)->with(['message' => $message, 'message_type' => $type]));
0 ignored issues
show
Bug introduced by
It seems like redirect($to)->with(arra...essage_type' => $type)) can also be of type Illuminate\Routing\Redirector; however, parameter $response of sendAndTerminate() 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

477
        sendAndTerminate(/** @scrutinizer ignore-type */ redirect($to)->with(['message' => $message, 'message_type' => $type]));
Loading history...
478
    }
479
480
    public static function icon($icon)
481
    {
482
        return '<i class=\'fa fa-'.$icon.'\'></i>';
483
    }
484
485
    public static function componentsPath($type = '')
486
    {
487
        $componentPath = implode(DIRECTORY_SEPARATOR, ['vendor', 'crocodicstudio', 'crudbooster', 'src', 'views', 'default', 'type_components', $type]);
488
        return base_path($componentPath);
489
490
    }
491
492
    public static function PublishedComponentsPath($type = '')
493
    {
494
        $Path = implode(DIRECTORY_SEPARATOR, ['views', 'vendor', 'crudbooster', 'type_components', $type]);
495
        return resource_path($Path);
496
    }
497
}
498