Completed
Push — master ( bd2e4c...921a2a )
by vijay
53:36
created

SettingsController::ReadConfigs()   C

Complexity

Conditions 11
Paths 44

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 26
c 1
b 0
f 0
nc 44
nop 0
dl 0
loc 40
rs 5.2653

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\Http\Controllers\Controller;
6
use App\Http\Requests\Common\SettingRequest;
7
use App\Model\Common\Setting;
8
use App\Model\Common\Template;
9
use App\Model\Plugin;
10
use Illuminate\Support\Collection;
11
12
class SettingsController extends Controller {
13
14
    public function __construct() {
15
        $this->middleware('auth', ['except' => 'checkPaymentGateway']);
16
        $this->middleware('admin', ['except' => 'checkPaymentGateway']);
17
    }
18
19
    public function Settings(Setting $settings) {
20
        if (!$settings->where('id', '1')->first()) {
21
            $settings->create(['company' => '']);
22
        }
23
        $setting = $settings->where('id', '1')->first();
24
        $template = new Template();
25
26
        return view('themes.default1.common.settings', compact('setting', 'template'));
27
    }
28
29
    public function UpdateSettings(Setting $settings, SettingRequest $request) {
30
        //dd($request);
31
        $setting = $settings->where('id', '1')->first();
32
        if ($request->has('password')) {
33
            $encrypt = $request->input('password');
34
            $doencrypt = \Crypt::encrypt($encrypt);
35
            $setting->password = $doencrypt;
36
        }
37
        if ($request->hasFile('logo')) {
38
            $name = $request->file('logo')->getClientOriginalName();
39
            $destinationPath = public_path('cart/img/logo');
40
            $request->file('logo')->move($destinationPath, $name);
41
            $setting->logo = $name;
42
        }
43
        $setting->fill($request->except('password', 'logo'))->save();
44
45
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
46
    }
47
48
    public function plugins() {
49
        return view('themes.default1.common.plugins');
50
    }
51
52
    public function getPlugin() {
53
        $plugins = $this->fetchConfig();
54
55
        return \Datatable::collection(new Collection($plugins))
56
                        ->searchColumns('name')
57
                        ->addColumn('name', function ($model) {
58
                            if (array_has($model, 'path')) {
59
                                if ($model['status'] == 0) {
60
                                    $activate = '<a href=' . url('plugin/status/' . $model['path']) . '>Activate</a>';
61
                                    $settings = ' ';
62
                                } else {
63
                                    $settings = '<a href=' . url($model['settings']) . '>Settings</a> | ';
64
                                    $activate = '<a href=' . url('plugin/status/' . $model['path']) . '>Deactivate</a>';
65
                                }
66
67
                                $delete = '<a href=  id=delete' . $model['path'] . ' data-toggle=modal data-target=#del' . $model['path'] . "><span style='color:red'>Delete</span></a>"
68
                                        . "<div class='modal fade' id=del" . $model['path'] . ">
69
                                            <div class='modal-dialog'>
70
                                                <div class=modal-content>  
71
                                                    <div class=modal-header>
72
                                                        <h4 class=modal-title>Delete</h4>
73
                                                    </div>
74
                                                    <div class=modal-body>
75
                                                       <p>Are you Sure ?</p>
76
                                                        <div class=modal-footer>
77
                                                            <button type=button class='btn btn-default pull-left' data-dismiss=modal id=dismis>" . \Lang::get('lang.close') . '</button>
78
                                                            <a href=' . url('plugin/delete/' . $model['path']) . "><button class='btn btn-danger'>Delete</button></a>
79
                                                        </div>
80
81
82
                                                    </div>
83
                                                </div>
84
                                            </div>
85
                                        </div>";
86
                                $action = '<br><br>' . $delete . ' | ' . $settings . $activate;
87
                            } else {
88
                                $action = '';
89
                            }
90
91
                            return ucfirst($model['name']) . $action;
92
                        })
93
                        ->addColumn('description', function ($model) {
94
                            return ucfirst($model['description']);
95
                        })
96
                        ->addColumn('author', function ($model) {
97
                            return ucfirst($model['author']);
98
                        })
99
                        ->addColumn('website', function ($model) {
100
                            return '<a href=' . $model['website'] . ' target=_blank>' . $model['website'] . '</a>';
101
                        })
102
                        ->addColumn('version', function ($model) {
103
                            return $model['version'];
104
                        })
105
                        ->make();
106
    }
107
108
    /**
109
     * Reading the Filedirectory.
110
     *
111
     * @return type
112
     */
113
    public function ReadPlugins() {
114
        $dir = app_path() . DIRECTORY_SEPARATOR . 'Plugins';
115
        $plugins = array_diff(scandir($dir), ['.', '..']);
116
117
        return $plugins;
118
    }
119
120
    /**
121
     * After plugin post.
122
     *
123
     * @param Request $request
124
     *
125
     * @return type
126
     */
127
    public function postPlugins(Request $request) {
128
        $v = $this->validate($request, ['plugin' => 'required|mimes:application/zip,zip,Zip']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $v is correct as $this->validate($request...lication/zip,zip,Zip')) (which targets Illuminate\Foundation\Va...tesRequests::validate()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
$v is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
129
        $plug = new Plugin();
130
        $file = $request->file('plugin');
131
        //dd($file);
132
        $destination = app_path() . DIRECTORY_SEPARATOR . 'Plugins';
133
        $zipfile = $file->getRealPath();
134
        /*
135
         * get the file name and remove .zip
136
         */
137
        $filename2 = $file->getClientOriginalName();
138
        $filename2 = str_replace('.zip', '', $filename2);
139
        $filename1 = ucfirst($file->getClientOriginalName());
140
        $filename = str_replace('.zip', '', $filename1);
141
        mkdir($destination . DIRECTORY_SEPARATOR . $filename);
142
        /*
143
         * extract the zip file using zipper
144
         */
145
        \Zipper::make($zipfile)->folder($filename2)->extractTo($destination . DIRECTORY_SEPARATOR . $filename);
146
147
        $file = app_path() . DIRECTORY_SEPARATOR . 'Plugins' . DIRECTORY_SEPARATOR . $filename; // Plugin file path
148
149
        if (file_exists($file)) {
150
            $seviceporvider = $file . DIRECTORY_SEPARATOR . 'ServiceProvider.php';
151
            $config = $file . DIRECTORY_SEPARATOR . 'config.php';
152
            if (file_exists($seviceporvider) && file_exists($config)) {
153
                /*
154
                 * move to faveo config
155
                 */
156
                $faveoconfig = config_path() . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $filename . '.php';
157
                if ($faveoconfig) {
158
159
                    //copy($config, $faveoconfig);
160
                    /*
161
                     * write provider list in app.php line 128
162
                     */
163
                    $app = base_path() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
164
                    $str = "\n\n\t\t\t'App\\Plugins\\$filename" . "\\ServiceProvider',";
165
                    $line_i_am_looking_for = 102;
166
                    $lines = file($app, FILE_IGNORE_NEW_LINES);
167
                    $lines[$line_i_am_looking_for] = $str;
168
                    file_put_contents($app, implode("\n", $lines));
169
                    $plug->create(['name' => $filename, 'path' => $filename, 'status' => 1]);
170
171
                    return redirect()->back()->with('success', 'Installed SuccessFully');
172
                } else {
173
                    /*
174
                     * delete if the plugin hasn't config.php and ServiceProvider.php
175
                     */
176
                    $this->deleteDirectory($file);
177
178
                    return redirect()->back()->with('fails', 'Their is no ' . $file);
179
                }
180
            } else {
181
                /*
182
                 * delete if the plugin hasn't config.php and ServiceProvider.php
183
                 */
184
                $this->deleteDirectory($file);
185
186
                return redirect()->back()->with('fails', 'Their is no <b>config.php or ServiceProvider.php</b>  ' . $file);
187
            }
188
        } else {
189
            /*
190
             * delete if the plugin Name is not equal to the folder name
191
             */
192
            $this->deleteDirectory($file);
193
194
            return redirect()->back()->with('fails', '<b>Plugin File Path is not exist</b>  ' . $file);
195
        }
196
    }
197
198
    /**
199
     * Delete the directory.
200
     *
201
     * @param type $dir
202
     *
203
     * @return bool
204
     */
205
    public function deleteDirectory($dir) {
206
        if (!file_exists($dir)) {
207
            return true;
208
        }
209
        if (!is_dir($dir)) {
210
            return unlink($dir);
211
        }
212
        foreach (scandir($dir) as $item) {
213
            if ($item == '.' || $item == '..') {
214
                continue;
215
            }
216
            chmod($dir . DIRECTORY_SEPARATOR . $item, 0777);
217
            if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
218
                return false;
219
            }
220
        }
221
        chmod($dir, 0777);
222
223
        return rmdir($dir);
224
    }
225
226
    public function ReadConfigs() {
227
        $dir = app_path() . DIRECTORY_SEPARATOR . 'Plugins' . DIRECTORY_SEPARATOR;
228
        $directories = scandir($dir);
229
        $files = [];
230
        foreach ($directories as $key => $file) {
231
            if ($file === '.' or $file === '..') {
232
                continue;
233
            }
234
235
            if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
236
                $files[$key] = $file;
237
            }
238
        }
239
        //dd($files);
240
        $config = [];
241
        $plugins = [];
242
        if (count($files) > 0) {
243
            foreach ($files as $key => $file) {
244
                $plugin = $dir . $file;
245
                $plugins[$key] = array_diff(scandir($plugin), ['.', '..', 'ServiceProvider.php']);
246
                $plugins[$key]['file'] = $plugin;
247
            }
248
            foreach ($plugins as $plugin) {
249
                $dir = $plugin['file'];
250
                //opendir($dir);
251
                if ($dh = opendir($dir)) {
252
                    while (($file = readdir($dh)) !== false) {
253
                        if ($file == 'config.php') {
254
                            $config[] = $dir . DIRECTORY_SEPARATOR . $file;
255
                        }
256
                    }
257
                    closedir($dh);
258
                }
259
            }
260
261
            return $config;
262
        } else {
263
            return 'null';
264
        }
265
    }
266
267
    public function fetchConfig() {
268
        $configs = $this->ReadConfigs();
269
        //dd($configs);
270
        $plugs = new Plugin();
271
        $fields = [];
272
        $attributes = [];
273
        if ($configs != 'null') {
274
            foreach ($configs as $key => $config) {
0 ignored issues
show
Bug introduced by
The expression $configs of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
275
                $fields[$key] = include $config;
276
            }
277
        }
278
        //dd($fields);
279
        if (count($fields) > 0) {
280
            foreach ($fields as $key => $field) {
281
                $plug = $plugs->where('name', $field['name'])->select('path', 'status')->orderBy('name')->get()->toArray();
282
                if ($plug) {
283
                    foreach ($plug as $i => $value) {
284
                        $attributes[$key]['path'] = $plug[$i]['path'];
285
                        $attributes[$key]['status'] = $plug[$i]['status'];
286
                    }
287
                } else {
288
                    $attributes[$key]['path'] = $field['name'];
289
                    $attributes[$key]['status'] = 0;
290
                }
291
                $attributes[$key]['name'] = $field['name'];
292
                $attributes[$key]['settings'] = $field['settings'];
293
                $attributes[$key]['description'] = $field['description'];
294
                $attributes[$key]['website'] = $field['website'];
295
                $attributes[$key]['version'] = $field['version'];
296
                $attributes[$key]['author'] = $field['author'];
297
            }
298
        }
299
        //dd($attributes);
300
        return $attributes;
301
    }
302
303
    public function deletePlugin($slug) {
304
        $dir = app_path() . DIRECTORY_SEPARATOR . 'Plugins' . DIRECTORY_SEPARATOR . $slug;
305
        $this->deleteDirectory($dir);
306
        /*
307
         * remove service provider from app.php
308
         */
309
        $str = "'App\\Plugins\\$slug" . "\\ServiceProvider',";
310
        $path_to_file = base_path() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
311
        $file_contents = file_get_contents($path_to_file);
312
        $file_contents = str_replace($str, '//', $file_contents);
313
        file_put_contents($path_to_file, $file_contents);
314
        $plugin = new Plugin();
315
        $plugin = $plugin->where('path', $slug)->first();
316
        if ($plugin) {
317
            $plugin->delete();
318
        }
319
320
        return redirect()->back()->with('success', 'Deleted Successfully');
321
    }
322
323
    public function statusPlugin($slug) {
324
        $plugs = new Plugin();
325
        $plug = $plugs->where('name', $slug)->first();
326
        if (!$plug) {
327
            $app = base_path() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
328
            $str = "\n'App\\Plugins\\$slug" . "\\ServiceProvider',";
329
            $line_i_am_looking_for = 102;
330
            $lines = file($app, FILE_IGNORE_NEW_LINES);
331
            $lines[$line_i_am_looking_for] = $str;
332
            file_put_contents($app, implode("\n", $lines));
333
            $plugs->create(['name' => $slug, 'path' => $slug, 'status' => 1]);
334
335
            return redirect()->back()->with('success', 'Status has changed');
336
        }
337
        $status = $plug->status;
338 View Code Duplication
        if ($status == 0) {
339
            $plug->status = 1;
340
341
            $app = base_path() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
342
            $str = "\n'App\\Plugins\\$slug" . "\\ServiceProvider',";
343
            $line_i_am_looking_for = 102;
344
            $lines = file($app, FILE_IGNORE_NEW_LINES);
345
            $lines[$line_i_am_looking_for] = $str;
346
            file_put_contents($app, implode("\n", $lines));
347
        }
348 View Code Duplication
        if ($status == 1) {
349
            $plug->status = 0;
350
            /*
351
             * remove service provider from app.php
352
             */
353
            $str = "\n'App\\Plugins\\$slug" . "\\ServiceProvider',";
354
            $path_to_file = base_path() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
355
356
            $file_contents = file_get_contents($path_to_file);
357
            $file_contents = str_replace($str, '//', $file_contents);
358
            file_put_contents($path_to_file, $file_contents);
359
        }
360
        $plug->save();
361
362
        return redirect()->back()->with('success', 'Status has changed');
363
    }
364
365
    public static function checkPaymentGateway($currency) {
366
        try {
367
368
            $plugins = new Plugin();
369
            $models = [];
370
            $gateways = [];
371
            $active_plugins = $plugins->where('status', 1)->get();
372
            if ($active_plugins->count() > 0) {
373
                foreach ($active_plugins as $plugin) {
374
                    array_push($models, \DB::table(strtolower($plugin->name)));
375
                }
376
                if (count($models) > 0) {
377
                    foreach ($models as $model) {
378
                        $currencies = explode(',', $model->first()->currencies);
379
                        if (in_array($currency, $currencies)) {
380
                            array_push($gateways, $model);
381
                        }
382
                    }
383
                }
384
            }
385
            return $gateways;
386
        } catch (\Exception $ex) {
387
            dd($ex);
388
        }
389
    }
390
391
}
392