Passed
Pull Request — master (#1108)
by Iman
07:29
created

CRUDBooster::getCurrentDashboardId()   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 getCurrentMenuId()
86
    {
87
        return GetCurrentX::getCurrentMenuId();
88
    }
89
90
    public static function adminPath($path = null)
91
    {
92
        return url(cbAdminPath().'/'.$path);
93
    }
94
95
    public static function deleteConfirm($redirectTo)
96
    {
97
        echo 'swal({   
98
				title: "'.cbTrans('delete_title_confirm').'",   
99
				text: "'.cbTrans('delete_description_confirm').'",   
100
				type: "warning",   
101
				showCancelButton: true,   
102
				confirmButtonColor: "#ff0000",   
103
				confirmButtonText: "'.cbTrans('confirmation_yes').'",  
104
				cancelButtonText: "'.cbTrans('confirmation_no').'",  
105
				closeOnConfirm: false }, 
106
				function(){  location.href="'.$redirectTo.'" });';
107
    }
108
109
    public static function getCurrentId()
110
    {
111
        return GetCurrentX::getCurrentId();
112
    }
113
114
    public static function getCurrentMethod()
115
    {
116
        return GetCurrentX::getCurrentMethod();
117
    }
118
119
    public static function isColumnNULL($table, $field)
120
    {
121
        return DbInspector::isColNull($table, $field);
122
    }
123
124
    public static function getValueFilter($field)
125
    {
126
        $filter = request('filter_column');
127
        if ($filter[$field]) {
128
            return $filter[$field]['value'];
129
        }
130
    }
131
132
    private static function getFilter($field, $index)
133
    {
134
        $filter = request('filter_column');
135
        if ($filter[$field]) {
136
            return $filter[$field][$index];
137
        }
138
    }
139
140
    public static function getSortingFilter($field)
141
    {
142
        return self::getFilter($field, 'sorting');
143
    }
144
145
    public static function getTypeFilter($field)
146
    {
147
        return self::getFilter($field, 'type');
148
    }
149
150
    public static function stringBetween($string, $start, $end)
151
    {
152
        $string = ' '.$string;
153
        $ini = strpos($string, $start);
154
        if ($ini == 0) {
155
            return '';
156
        }
157
        $ini += strlen($start);
158
        $len = strpos($string, $end, $ini) - $ini;
159
160
        return substr($string, $ini, $len);
161
    }
162
163
    public static function first($table, $id)
164
    {
165
        $table = self::parseSqlTable($table)['table'];
166
        if (! is_array($id)) {
167
            $pk = self::pk($table);
168
169
            return DB::table($table)->where($pk, $id)->first();
170
        }
171
172
        $first = DB::table($table);
173
        foreach ($id as $k => $v) {
174
            $first->where($k, $v);
175
        }
176
177
        return $first->first();
178
    }
179
180
    public static function pk($table)
181
    {
182
        return DbInspector::findPK($table);
183
    }
184
185
    public static function valid($rules = [], $type = 'json')
186
    {
187
        $validator = Validator::make(request()->all(), $rules);
188
189
        if (!$validator->fails()) {
190
            return true;
191
        }
192
193
        $message = $validator->errors()->all();
194
195
        if ($type == 'json') {
196
            $result = [];
197
            $result['api_status'] = 0;
198
            $result['api_message'] = implode(', ', $message);
199
            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

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

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

422
        sendAndTerminate(/** @scrutinizer ignore-type */ redirect($to)->with(['message' => $message, 'message_type' => $type]));
Loading history...
423
    }
424
425
    public static function icon($icon)
426
    {
427
        return '<i class=\'fa fa-'.$icon.'\'></i>';
428
    }
429
430
    public static function componentsPath($type = '')
431
    {
432
        $componentPath = implode(DIRECTORY_SEPARATOR, ['vendor', 'crocodicstudio', 'crudbooster', 'src', 'views', 'default', 'type_components', $type]);
433
        return base_path($componentPath);
434
435
    }
436
437
    public static function PublishedComponentsPath($type = '')
438
    {
439
        $Path = implode(DIRECTORY_SEPARATOR, ['views', 'vendor', 'crudbooster', 'type_components', $type]);
440
        return resource_path($Path);
441
    }
442
}
443