Passed
Push — master ( 01e728...d6a5af )
by Iman
08:33 queued 03:15
created

CRUDBooster::componentsPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
nc 1
nop 1
dl 0
loc 4
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\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
        return DbInspector::getForeignKey($parent_table, $child_table);
199
    }
200
201
    public static function getTableForeignKey($fieldName)
202
    {
203
        if (substr($fieldName, 0, 3) == 'id_' || substr($fieldName, -3) == '_id') {
204
            return str_replace(['_id', 'id_'], '', $fieldName);
205
        }
206
    }
207
208
    public static function isForeignKey($fieldName)
209
    {
210
        return DbInspector::isForeignKeey($fieldName);
211
    }
212
213
    public static function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
214
    {
215
        return \crocodicstudio\crudbooster\CBCoreModule\Index\ViewHelpers::urlFilterColumn($key, $type, $value, $singleSorting);
216
    }
217
    public static function mainpath($path = null)
218
    {
219
        $controllerName = strtok(Route::currentRouteAction(), '@');
220
        // $controllerName = array_pop(explode('\\', $controllerName));
221
        $controllerName = basename($controllerName);
222
        $route_url = route($controllerName.'GetIndex');
223
224
        if (! $path) {
225
            return trim($route_url, '/');
226
        }
227
228
        if (substr($path, 0, 1) == '?') {
229
            return trim($route_url, '/').$path;
230
        }
231
232
        return $route_url.'/'.$path;
233
    }
234
235
    public static function insertLog($description)
236
    {
237
        LogsRepository::insertLog('crudbooster: '.$description, self::myId());
238
    }
239
240
    public static function insertTryLog($action, $name = '')
241
    {
242
        self::insertLog(trans("logging.log_try_".$action, ['name' => $name, 'module' => self::getCurrentModule()]));
243
    }
244
245
    public static function myId()
246
    {
247
        return session('admin_id');
248
    }
249
250
    public static function referer()
251
    {
252
        return Request::server('HTTP_REFERER');
253
    }
254
255
    public static function listTables()
256
    {
257
        return DbInspector::listTables();
258
    }
259
260
    public static function listCbTables()
261
    {
262
        $tablesList = [];
263
        foreach (self::listTables() as $tableObj) {
264
265
            $tableName = $tableObj->TABLE_NAME;
266
            if ($tableName == config('database.migrations')) {
267
                continue;
268
            }
269
            if (substr($tableName, 0, 4) == 'cms_' && $tableName != 'cms_users') {
270
                continue;
271
            }
272
273
            $tablesList[] = $tableName;
274
        }
275
276
        return $tablesList;
277
    }
278
279
    public static function getUrlParameters($exception = null)
280
    {
281
        return ViewHelpers::getUrlParameters($exception);
282
    }
283
284
/*    public static function isExistsController($table)
285
    {
286
        $ctrlName = ucwords(str_replace('_', ' ', $table));
287
        $ctrlName = str_replace(' ', '', $ctrlName).'Controller.php';
288
        $path = base_path(controllers_dir());
289
        $path2 = base_path(controllers_dir()."ControllerMaster/");
290
291
        if (file_exists($path.'Admin'.$ctrlName) || file_exists($path2.'Admin'.$ctrlName) || file_exists($path2.$ctrlName)) {
292
            return true;
293
        }
294
295
        return false;
296
    }*/
297
298
    public static function getTableColumns($table)
299
    {
300
        return DbInspector::getTableCols($table);
301
    }
302
303
    public static function getNameTable($columns)
304
    {
305
        return DbInspector::colName($columns);
306
    }
307
308
    public static function routeController($prefix, $controller, $namespace = null)
309
    {
310
        RouteController::routeController($prefix, $controller, $namespace);
311
    }
312
313
    /*
314
    | -------------------------------------------------------------
315
    | Alternate route for Laravel Route::controller
316
    | -------------------------------------------------------------
317
    | $prefix       = path of route
318
    | $controller   = controller name
319
    | $namespace    = namespace of controller (optional)
320
    |
321
    */
322
323
    public static function denyAccess()
324
    {
325
        static::redirect(static::adminPath(), cbTrans('denied_access'));
326
    }
327
328
    public static function redirect($to, $message, $type = 'warning')
329
    {
330
        if (Request::ajax()) {
331
            sendAndTerminate(response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]));
332
        }
333
334
        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

334
        sendAndTerminate(/** @scrutinizer ignore-type */ redirect($to)->with(['message' => $message, 'message_type' => $type]));
Loading history...
335
    }
336
337
    public static function icon($icon)
338
    {
339
        return '<i class=\'fa fa-'.$icon.'\'></i>';
340
    }
341
342
    public static function componentsPath($type = '')
343
    {
344
        $componentPath = implode(DIRECTORY_SEPARATOR, ['vendor', 'crocodicstudio', 'crudbooster', 'src', 'views', 'default', 'type_components', $type]);
345
        return base_path($componentPath);
346
347
    }
348
349
    public static function PublishedComponentsPath($type = '')
350
    {
351
        $Path = implode(DIRECTORY_SEPARATOR, ['views', 'vendor', 'crudbooster', 'type_components', $type]);
352
        return resource_path($Path);
353
    }
354
}
355