Passed
Push — master ( 3388c8...01e728 )
by Iman
08:15 queued 02:52
created

CRUDBooster::getUrlParameters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use crocodicstudio\crudbooster\CBCoreModule\CbUsersRepo;
6
use crocodicstudio\crudbooster\CBCoreModule\RouteController;
7
use crocodicstudio\crudbooster\CBCoreModule\ViewHelpers;
8
use crocodicstudio\crudbooster\Modules\LogsModule\LogsRepository;
9
use crocodicstudio\crudbooster\Modules\PrivilegeModule\PrivilegeHelpers;
10
use Session;
11
use Request;
12
use Schema;
13
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...
14
use DB;
15
use Route;
16
use Config;
17
use Validator;
18
19
class CRUDBooster
20
{
21
    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...
22
23
    public static function get($table, $string_conditions = null, $orderby = null, $limit = null, $skip = null)
24
    {
25
        $table = self::parseSqlTable($table);
26
        $table = $table['table'];
27
        $query = DB::table($table);
28
        if ($string_conditions) {
29
            $query->whereraw($string_conditions);
30
        }
31
        if ($orderby) {
32
            $query->orderbyraw($orderby);
33
        }
34
        if ($limit) {
35
            $query->take($limit);
36
        }
37
        if ($skip) {
38
            $query->skip($skip);
39
        }
40
41
        return $query->get();
42
    }
43
44
    public static function parseSqlTable($table)
45
    {
46
        $f = explode('.', $table);
47
48
        if (count($f) == 1) {
49
            return ["table" => $f[0], "database" => cbConfig('MAIN_DB_DATABASE')];
50
        }
51
        if (count($f) == 2) {
52
            return ["database" => $f[0], "table" => $f[1]];
53
        }
54
55
        if (count($f) == 3) {
56
            return ["table" => $f[0], "schema" => $f[1], "table" => $f[2]];
57
        }
58
59
        return false;
60
    }
61
62
    public static function me()
63
    {
64
        return CbUsersRepo::find(session('admin_id'));
65
    }
66
67
    public static function myName()
68
    {
69
        return session('admin_name');
70
    }
71
72
    public static function myPhoto()
73
    {
74
        return session('admin_photo');
75
    }
76
77
    public static function isLocked()
78
    {
79
        return session('admin_lock');
80
    }
81
82
    public static function getCurrentModule()
83
    {
84
        return GetCurrentX::getCurrentModule();
85
    }
86
87
    public static function getCurrentMenuId()
88
    {
89
        return GetCurrentX::getCurrentMenuId();
90
    }
91
92
    public static function adminPath($path = null)
93
    {
94
        return url(cbAdminPath().'/'.$path);
95
    }
96
97
    public static function deleteConfirm($redirectTo)
98
    {
99
        ViewHelpers::delConfirm($redirectTo);
100
    }
101
102
    public static function getCurrentId()
103
    {
104
        return GetCurrentX::getCurrentId();
105
    }
106
107
    public static function getCurrentMethod()
108
    {
109
        return GetCurrentX::getCurrentMethod();
110
    }
111
112
    public static function isColumnNULL($table, $field)
113
    {
114
        return DbInspector::isColNull($table, $field);
115
    }
116
117
    public static function getValueFilter($field)
118
    {
119
        self::getFilter($field, 'value');
120
    }
121
122
    private static function getFilter($field, $index)
123
    {
124
        $filter = request('filter_column');
125
        if ($filter[$field]) {
126
            return $filter[$field][$index];
127
        }
128
    }
129
130
    public static function getSortingFilter($field)
131
    {
132
        return self::getFilter($field, 'sorting');
133
    }
134
135
    public static function getTypeFilter($field)
136
    {
137
        return self::getFilter($field, 'type');
138
    }
139
140
    public static function stringBetween($string, $start, $end)
141
    {
142
        $string = ' '.$string;
143
        $ini = strpos($string, $start);
144
        if ($ini == 0) {
145
            return '';
146
        }
147
        $ini += strlen($start);
148
        $len = strpos($string, $end, $ini) - $ini;
149
150
        return substr($string, $ini, $len);
151
    }
152
153
    public static function first($table, $id)
154
    {
155
        $table = self::parseSqlTable($table)['table'];
156
        if (! is_array($id)) {
157
            $pk = self::pk($table);
158
159
            return DB::table($table)->where($pk, $id)->first();
160
        }
161
162
        $first = DB::table($table);
163
        foreach ($id as $k => $v) {
164
            $first->where($k, $v);
165
        }
166
167
        return $first->first();
168
    }
169
170
    public static function pk($table)
171
    {
172
        return DbInspector::findPK($table);
173
    }
174
175
    public static function valid($rules = [], $type = 'json')
176
    {
177
        $validator = Validator::make(request()->all(), $rules);
178
179
        if (!$validator->fails()) {
180
            return true;
181
        }
182
183
        $message = $validator->errors()->all();
184
185
        if ($type == 'json') {
186
            $result = [];
187
            $result['api_status'] = 0;
188
            $result['api_message'] = implode(', ', $message);
189
            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

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

360
        sendAndTerminate(/** @scrutinizer ignore-type */ redirect($to)->with(['message' => $message, 'message_type' => $type]));
Loading history...
361
    }
362
363
    public static function icon($icon)
364
    {
365
        return '<i class=\'fa fa-'.$icon.'\'></i>';
366
    }
367
368
    public static function componentsPath($type = '')
369
    {
370
        $componentPath = implode(DIRECTORY_SEPARATOR, ['vendor', 'crocodicstudio', 'crudbooster', 'src', 'views', 'default', 'type_components', $type]);
371
        return base_path($componentPath);
372
373
    }
374
375
    public static function PublishedComponentsPath($type = '')
376
    {
377
        $Path = implode(DIRECTORY_SEPARATOR, ['views', 'vendor', 'crudbooster', 'type_components', $type]);
378
        return resource_path($Path);
379
    }
380
}
381