Passed
Push — master ( 06bf02...b3147e )
by Ferry
03:01
created

CB::routeGroupBackend()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use Cache;
6
use crocodicstudio\crudbooster\exceptions\CBValidationException;
7
use DB;
8
use Illuminate\Validation\ValidationException;
9
use Image;
10
use Request;
11
use Route;
12
use Schema;
13
use Session;
14
use Storage;
15
use Validator;
16
17
class CB
18
{
19
20
    public function getRoleByName($roleName) {
21
        return $this->find("cb_roles",['name'=>$roleName]);
22
    }
23
24
    public function fcm() {
25
        return new FCM();
26
    }
27
28
    public function sidebar() {
29
        return new SidebarMenus();
30
    }
31
32
    public function session() {
33
        return new UserSession();
34
    }
35
36
    public function getDeveloperUrl($path = null) {
37
        $path = ($path)?"/".trim($path,"/"):null;
38
        return url(cbConfig("DEV_PATH")).$path;
0 ignored issues
show
Bug introduced by
Are you sure url(cbConfig('DEV_PATH')) of type Illuminate\Contracts\Routing\UrlGenerator|string 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

38
        return /** @scrutinizer ignore-type */ url(cbConfig("DEV_PATH")).$path;
Loading history...
39
    }
40
41
    public function getProfileUrl() {
42
        return $this->getAdminUrl()."/profile";
43
    }
44
45
    public function getLogoutUrl() {
46
        return $this->getAdminUrl()."/logout";
47
    }
48
49
    public function getLoginUrl() {
50
        return $this->getAdminUrl("login");
51
    }
52
53
    public function getAdminUrl($path = null) {
54
        $path = ($path)?"/".trim($path,"/"):null;
55
        return url(cbConfig("ADMIN_PATH")).$path;
0 ignored issues
show
Bug introduced by
Are you sure url(cbConfig('ADMIN_PATH')) of type Illuminate\Contracts\Routing\UrlGenerator|string 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

55
        return /** @scrutinizer ignore-type */ url(cbConfig("ADMIN_PATH")).$path;
Loading history...
56
    }
57
58
    public function getAppName() {
59
        return env("APP_NAME","CRUDBOOSTER");
60
    }
61
62
    public function uploadBase64($value)
63
    {
64
        $fileData = base64_decode($value);
65
        $mime_type = finfo_buffer(finfo_open(), $fileData, FILEINFO_MIME_TYPE);
66
        if($mime_type) {
67
            if($mime_type = explode('/', $mime_type)) {
68
                $ext = $mime_type[1];
69
                if($ext) {
70
                    $filePath = 'uploads/'.date('Y-m');
71
                    Storage::makeDirectory($filePath);
72
                    $filename = sha1(strRandom(5)).'.'.$ext;
73
                    if (Storage::put($filePath.'/'.$filename, $fileData)) {
74
                        self::resizeImage($filePath.'/'.$filename);
0 ignored issues
show
Bug Best Practice introduced by
The method crocodicstudio\crudboost...lpers\CB::resizeImage() is not static, but was called statically. ( Ignorable by Annotation )

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

74
                        self::/** @scrutinizer ignore-call */ 
75
                              resizeImage($filePath.'/'.$filename);
Loading history...
75
                        return $filePath.'/'.$filename;
76
                    }
77
                }
78
            }
79
        }
80
        return null;
81
    }
82
83
    public function uploadFile($name, $encrypt = true, $resize_width = 1024, $resize_height = null)
84
    {
85
        if (request()->hasFile($name)) {
86
87
            $file = request()->file($name);
88
            $ext = $file->getClientOriginalExtension();
89
            if(in_array($ext,cbConfig("UPLOAD_FILE_EXTENSION_ALLOWED"))) {
90
                $filename = slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
91
                $file_path = 'uploads/'.date('Y-m');
92
93
                //Create Directory Monthly
94
                Storage::makeDirectory($file_path);
95
96
                if ($encrypt == true) {
97
                    $filename = sha1(strRandom(5)).'.'.$ext;
98
                } else {
99
                    $filename = slug($filename, '_').'.'.$ext;
100
                }
101
102
                if (Storage::putFileAs($file_path, $file, $filename)) {
103
                    if($resize_width || $resize_height) {
104
                        $this->resizeImage($file_path.'/'.$filename, $resize_width, $resize_height);
105
                    }
106
                    return $file_path.'/'.$filename;
107
                } else {
108
                    throw new \Exception("Something went wrong, file can't upload!");
109
                }
110
            }else{
111
                throw new \Exception("The file format is not allowed!");
112
            }
113
114
        } else {
115
            throw new \Exception("There is no file send to server!");
116
        }
117
    }
118
119
    public function resizeImage($fullFilePath, $resize_width = null, $resize_height = null, $qty = 100, $thumbQty = 75)
0 ignored issues
show
Unused Code introduced by
The parameter $thumbQty is not used and could be removed. ( Ignorable by Annotation )

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

119
    public function resizeImage($fullFilePath, $resize_width = null, $resize_height = null, $qty = 100, /** @scrutinizer ignore-unused */ $thumbQty = 75)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
120
    {
121
        $images_ext = cbConfig("UPLOAD_IMAGE_EXTENSION_ALLOWED");
122
123
        $filename = basename($fullFilePath);
124
        $file_path = trim(str_replace($filename, '', $fullFilePath), '/');
125
        $ext = pathinfo($fullFilePath, PATHINFO_EXTENSION);
126
127
        if (in_array(strtolower($ext), $images_ext)) {
128
129
            if ($resize_width && $resize_height) {
130
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
131
                $img->fit($resize_width, $resize_height);
132
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
133
            } elseif ($resize_width && ! $resize_height) {
134
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
135
                $img->resize($resize_width, null, function ($constraint) {
136
                    $constraint->aspectRatio();
137
                });
138
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
139
            } elseif (! $resize_width && $resize_height) {
140
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
141
                $img->resize(null, $resize_height, function ($constraint) {
142
                    $constraint->aspectRatio();
143
                });
144
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
145
            } else {
146
                $img = Image::make(storage_path('app/'.$file_path.'/'.$filename));
147
                if ($img->width() > 1300) {
148
                    $img->resize(1300, null, function ($constraint) {
149
                        $constraint->aspectRatio();
150
                    });
151
                }
152
                $img->save(storage_path('app/'.$file_path.'/'.$filename), $qty);
153
            }
154
        }
155
    }
156
157
    public function update($table, $id, $data)
158
    {
159
        DB::table($table)
160
            ->where($this->pk($table), $id)
161
            ->update($data);
162
    }
163
164
    public function updateCompact($table, $id, $params) {
165
        $data = [];
166
        foreach ($params as $param) {
167
            $data[$param] = request($param);
168
        }
169
        $this->update($table, $id, $data);
170
    }
171
172
    public function find($table, $id)
173
    {
174
        if (is_array($id)) {
175
            $first = DB::table($table);
176
            foreach ($id as $k => $v) {
177
                $first->where($k, $v);
178
            }
179
180
            return $first->first();
181
        } else {
182
            $pk = $this->pk($table);
183
184
            return DB::table($table)->where($pk, $id)->first();
185
        }
186
    }
187
188
    public function findAll($table, $condition_array = [])
189
    {
190
        return DB::table($table)->where($condition_array)->get();
191
    }
192
193
    public function redirectBack($message, $type = 'warning')
194
    {
195
        if (request()->ajax()) {
196
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $_SERVER['HTTP_REFERER']]);
197
        } else {
198
            return redirect()->back()->withInput()
199
                ->with(['message'=> $message, 'message_type'=> $type]);
200
        }
201
    }
202
203
    public function redirect($to, $message, $type = 'warning')
204
    {
205
        if (Request::ajax()) {
206
            return response()->json(['message' => $message, 'message_type' => $type, 'redirect_url' => $to]);
207
        } else {
208
            return redirect($to)->with(['message' => $message, 'message_type' => $type]);
209
        }
210
    }
211
212
213
    public function getCurrentMethod()
214
    {
215
        $action = str_replace("App\Http\Controllers", "", Route::currentRouteAction());
216
        $atloc = strpos($action, '@') + 1;
217
        $method = substr($action, $atloc);
218
219
        return $method;
220
    }
221
222
    public function stringBetween($string, $start, $end)
223
    {
224
        $string = ' '.$string;
225
        $ini = strpos($string, $start);
226
        if ($ini == 0) {
227
            return '';
228
        }
229
        $ini += strlen($start);
230
        $len = strpos($string, $end, $ini) - $ini;
231
232
        return substr($string, $ini, $len);
233
    }
234
235
    /**
236
     * @param array $rules
237
     * @param array $messages
238
     * @throws CBValidationException
239
     */
240
    public function validation($rules = [], $messages = [])
241
    {
242
        $input_arr = request()->all();
243
244
        foreach ($rules as $a => $b) {
245
            if (is_int($a)) {
246
                $rules[$b] = 'required';
247
            } else {
248
                $rules[$a] = $b;
249
            }
250
        }
251
252
        $validator = Validator::make($input_arr, $rules, $messages);
253
        if ($validator->fails()) {
254
            $message = $validator->errors()->all();
255
            throw new CBValidationException(implode("; ",$message));
256
        }
257
    }
258
259
    public function pk($table)
260
    {
261
        return $this->findPrimaryKey($table);
262
    }
263
264
    public function findPrimaryKey($table)
265
    {
266
        $pk = DB::getDoctrineSchemaManager()->listTableDetails($table)->getPrimaryKey();
267
        if(!$pk) {
268
            return null;
269
        }
270
        return $pk->getColumns()[0];
271
    }
272
273
    public function urlFilterColumn($key, $type, $value = '', $singleSorting = true)
274
    {
275
        $params = Request::all();
276
        $mainpath = trim(self::mainpath(), '/');
0 ignored issues
show
Bug introduced by
The method mainpath() does not exist on crocodicstudio\crudbooster\helpers\CB. ( Ignorable by Annotation )

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

276
        $mainpath = trim(self::/** @scrutinizer ignore-call */ mainpath(), '/');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
277
        $key = sanitizeXSS($key);
278
        $type = sanitizeXSS($type);
279
        $value = sanitizeXSS($value);
280
281
        if ($params['filter_column'] && $singleSorting) {
282
            foreach ($params['filter_column'] as $k => $filter) {
283
                foreach ($filter as $t => $val) {
284
                    if ($t == 'sorting') {
285
                        unset($params['filter_column'][$k]['sorting']);
286
                    }
287
                }
288
            }
289
        }
290
291
        $params['filter_column'][$key][$type] = $value;
292
293
        if (isset($params)) {
294
            return $mainpath.'?'.http_build_query($params);
295
        } else {
296
            return $mainpath.'?filter_column['.$key.']['.$type.']='.$value;
297
        }
298
    }
299
300
301
    public function getUrlParameters($exception = null)
302
    {
303
        $get = request()->all();
304
        $inputhtml = '';
305
306
        if ($get) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $get of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
307
            if (is_array($exception)) {
308
                foreach ($exception as $e) {
309
                    unset($get[$e]);
310
                }
311
            }
312
            $string_parameters = http_build_query($get);
313
            $string_parameters_array = explode('&', $string_parameters);
314
            foreach ($string_parameters_array as $s) {
315
                $part = explode('=', $s);
316
                if(isset($part[0]) && isset($part[1])) {
317
                    $name = htmlspecialchars(urldecode($part[0]));
318
                    $name = strip_tags($name);
319
                    $value = htmlspecialchars(urldecode($part[1]));
320
                    $value = strip_tags($value);
321
                    if ($name) {
322
                        $inputhtml .= "<input type='hidden' name='$name' value='$value'/>\n";
323
                    }
324
                }
325
            }
326
        }
327
328
        return $inputhtml;
329
    }
330
331
332
    public function routeGet($prefix, $controller) {
333
        $alias = str_replace("@"," ", $controller);
334
        $alias = ucwords($alias);
335
        $alias = str_replace(" ","",$alias);
336
        Route::get($prefix, ['uses' => $controller, 'as' => $alias]);
337
    }
338
339
    public function routePost($prefix, $controller) {
340
        $alias = str_replace("@"," ", $controller);
341
        $alias = ucwords($alias);
342
        $alias = str_replace(" ","",$alias);
343
        Route::post($prefix, ['uses' => $controller, 'as' => $alias]);
344
    }
345
346
    public function routeGroupBackend(callable $callback, $namespace = 'crocodicstudio\crudbooster\controllers') {
347
        Route::group([
348
            'middleware' => ['web', \crocodicstudio\crudbooster\middlewares\CBBackend::class],
349
            'prefix' => cbConfig('ADMIN_PATH'),
350
            'namespace' => $namespace,
351
        ], $callback);
352
    }
353
354
    /*
355
    | --------------------------------------------------------------------------------------------------------------
356
    | Alternate route for Laravel Route::controller
357
    | --------------------------------------------------------------------------------------------------------------
358
    | $prefix       = path of route
359
    | $controller   = controller name
360
    | $namespace    = namespace of controller (optional)
361
    |
362
    */
363
    public function routeController($prefix, $controller, $namespace = null)
364
    {
365
366
        $prefix = trim($prefix, '/').'/';
367
368
        $namespace = ($namespace) ?: 'App\Http\Controllers';
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
                    if (substr($method->name, 0, 3) == 'get') {
380
                        $method_name = substr($method->name, 3);
381
                        $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

381
                        $slug = array_filter(/** @scrutinizer ignore-type */ preg_split('/(?=[A-Z])/', $method_name));
Loading history...
382
                        $slug = strtolower(implode('-', $slug));
383
                        $slug = ($slug == 'index') ? '' : $slug;
384
                        Route::get($prefix.$slug.$wildcards, ['uses' => $controller.'@'.$method->name, 'as' => $controller.'Get'.$method_name]);
385
                    } elseif (substr($method->name, 0, 4) == 'post') {
386
                        $method_name = substr($method->name, 4);
387
                        $slug = array_filter(preg_split('/(?=[A-Z])/', $method_name));
388
                        Route::post($prefix.strtolower(implode('-', $slug)).$wildcards, [
389
                            'uses' => $controller.'@'.$method->name,
390
                            'as' => $controller.'Post'.$method_name,
391
                        ]);
392
                    }
393
                }
394
            }
395
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
396
397
        }
398
    }
399
}
400