Passed
Pull Request — master (#1102)
by Iman
06:57
created

CRUDBooster::isLocked()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
nc 1
nop 0
dl 0
loc 3
c 0
b 0
f 0
cc 1
rs 10
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use crocodicstudio\crudbooster\CBCoreModule\CbUsersRepo;
6
use crocodicstudio\crudbooster\Modules\LogsModule\LogsRepository;
7
use crocodicstudio\crudbooster\Modules\PrivilegeModule\PrivilegeHelpers;
8
use Session;
9
use Request;
10
use Schema;
11
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...
12
use DB;
13
use Route;
14
use Config;
15
use Validator;
16
17
class CRUDBooster
18
{
19
    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...
20
21
    public static function get($table, $string_conditions = null, $orderby = null, $limit = null, $skip = null)
22
    {
23
        $table = self::parseSqlTable($table);
24
        $table = $table['table'];
25
        $query = DB::table($table);
26
        if ($string_conditions) {
27
            $query->whereraw($string_conditions);
28
        }
29
        if ($orderby) {
30
            $query->orderbyraw($orderby);
31
        }
32
        if ($limit) {
33
            $query->take($limit);
34
        }
35
        if ($skip) {
36
            $query->skip($skip);
37
        }
38
39
        return $query->get();
40
    }
41
42
    public static function parseSqlTable($table)
43
    {
44
        $f = explode('.', $table);
45
46
        if (count($f) == 1) {
47
            return ["table" => $f[0], "database" => cbConfig('MAIN_DB_DATABASE')];
48
        }
49
        if (count($f) == 2) {
50
            return ["database" => $f[0], "table" => $f[1]];
51
        }
52
53
        if (count($f) == 3) {
54
            return ["table" => $f[0], "schema" => $f[1], "table" => $f[2]];
55
        }
56
57
        return false;
58
    }
59
60
    public static function me()
61
    {
62
        return CbUsersRepo::find(session('admin_id'));
63
    }
64
65
    public static function myName()
66
    {
67
        return session('admin_name');
68
    }
69
70
    public static function myPhoto()
71
    {
72
        return session('admin_photo');
73
    }
74
75
    public static function isLocked()
76
    {
77
        return session('admin_lock');
78
    }
79
80
    public static function getCurrentModule()
81
    {
82
        return GetCurrentX::getCurrentModule();
83
    }
84
85
    public static function getCurrentDashboardId()
86
    {
87
        return GetCurrentX::getCurrentDashboardId();
88
    }
89
90
    public static function getCurrentMenuId()
91
    {
92
        return GetCurrentX::getCurrentMenuId();
93
    }
94
95
    public static function adminPath($path = null)
96
    {
97
        return url(cbAdminPath().'/'.$path);
98
    }
99
100
    public static function deleteConfirm($redirectTo)
101
    {
102
        echo 'swal({   
103
				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

103
				title: "'./** @scrutinizer ignore-type */ cbTrans('delete_title_confirm').'",   
Loading history...
104
				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

104
				text: "'./** @scrutinizer ignore-type */ cbTrans('delete_description_confirm').'",   
Loading history...
105
				type: "warning",   
106
				showCancelButton: true,   
107
				confirmButtonColor: "#ff0000",   
108
				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

108
				confirmButtonText: "'./** @scrutinizer ignore-type */ cbTrans('confirmation_yes').'",  
Loading history...
109
				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

109
				cancelButtonText: "'./** @scrutinizer ignore-type */ cbTrans('confirmation_no').'",  
Loading history...
110
				closeOnConfirm: false }, 
111
				function(){  location.href="'.$redirectTo.'" });';
112
    }
113
114
    public static function getCurrentId()
115
    {
116
        return GetCurrentX::getCurrentId();
117
    }
118
119
    public static function getCurrentMethod()
120
    {
121
        return GetCurrentX::getCurrentMethod();
122
    }
123
124
    public static function isColumnNULL($table, $field)
125
    {
126
        return DbInspector::isColNull($table, $field);
127
    }
128
129
    public static function getValueFilter($field)
130
    {
131
        $filter = request('filter_column');
132
        if ($filter[$field]) {
133
            return $filter[$field]['value'];
134
        }
135
    }
136
137
    private static function getFilter($field, $index)
138
    {
139
        $filter = request('filter_column');
140
        if ($filter[$field]) {
141
            return $filter[$field][$index];
142
        }
143
    }
144
145
    public static function getSortingFilter($field)
146
    {
147
        return self::getFilter($field, 'sorting');
148
    }
149
150
    public static function getTypeFilter($field)
151
    {
152
        return self::getFilter($field, 'type');
153
    }
154
155
    public static function stringBetween($string, $start, $end)
156
    {
157
        $string = ' '.$string;
158
        $ini = strpos($string, $start);
159
        if ($ini == 0) {
160
            return '';
161
        }
162
        $ini += strlen($start);
163
        $len = strpos($string, $end, $ini) - $ini;
164
165
        return substr($string, $ini, $len);
166
    }
167
168
    public static function first($table, $id)
169
    {
170
        $table = self::parseSqlTable($table)['table'];
171
        if (! is_array($id)) {
172
            $pk = self::pk($table);
173
174
            return DB::table($table)->where($pk, $id)->first();
175
        }
176
177
        $first = DB::table($table);
178
        foreach ($id as $k => $v) {
179
            $first->where($k, $v);
180
        }
181
182
        return $first->first();
183
    }
184
185
    public static function pk($table)
186
    {
187
        return self::findPrimaryKey($table);
188
    }
189
190
    public static function findPrimaryKey($table)
191
    {
192
        return DbInspector::findPK($table);
193
    }
194
195
    public static function valid($rules = [], $type = 'json')
196
    {
197
        $validator = Validator::make(request()->all(), $rules);
198
199
        if (!$validator->fails()) {
200
            return true;
201
        }
202
203
        $message = $validator->errors()->all();
204
205
        if ($type == 'json') {
206
            $result = [];
207
            $result['api_status'] = 0;
208
            $result['api_message'] = implode(', ', $message);
209
            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

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

393
                    $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
394
                    $slug = strtolower(implode('-', $slug));
395
                    $slug = ($slug == 'index') ? '' : $slug;
396
                    Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller.'Get'.$method_name]);
397
                } elseif (substr($method->name, 0, 4) == 'post') {
398
                    $method_name = substr($method->name, 4);
399
                    $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
400
                    Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
401
                            'uses' => $controller.'@'.$method->name,
402
                            'as' => $controller.'Post'.$method_name,
403
                        ]);
404
                }
405
            }
406
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
407
408
        }
409
    }
410
411
    /*
412
    | -------------------------------------------------------------
413
    | Alternate route for Laravel Route::controller
414
    | -------------------------------------------------------------
415
    | $prefix       = path of route
416
    | $controller   = controller name
417
    | $namespace    = namespace of controller (optional)
418
    |
419
    */
420
421
    public static function denyAccess()
422
    {
423
        static::redirect(static::adminPath(), cbTrans('denied_access'));
424
    }
425
426
    public static function redirect($to, $message, $type = 'warning')
427
    {
428
        if (Request::ajax()) {
429
            sendAndTerminate(response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]));
430
        }
431
432
        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

432
        sendAndTerminate(/** @scrutinizer ignore-type */ redirect($to)->with(['message' => $message, 'message_type' => $type]));
Loading history...
433
    }
434
435
    public static function icon($icon)
436
    {
437
        return '<i class=\'fa fa-'.$icon.'\'></i>';
438
    }
439
440
    public static function componentsPath($type = '')
441
    {
442
        $componentPath = implode(DIRECTORY_SEPARATOR, ['vendor', 'crocodicstudio', 'crudbooster', 'src', 'views', 'default', 'type_components', $type]);
443
        return base_path($componentPath);
444
445
    }
446
447
    public static function PublishedComponentsPath($type = '')
448
    {
449
        $Path = implode(DIRECTORY_SEPARATOR, ['views', 'vendor', 'crudbooster', 'type_components', $type]);
450
        return resource_path($Path);
451
    }
452
}
453