Completed
Push — development ( 3e307e...0dc251 )
by Ashutosh
11:44
created

ProductController   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 559
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 49
eloc 302
dl 0
loc 559
rs 8.48
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 40 1
A index() 0 8 2
A getSubscriptionCheckScript() 0 15 1
A create() 0 24 2
B getProducts() 0 61 7
A edit() 0 26 2
B destroy() 0 55 6
A save() 0 24 3
A adminDownload() 0 24 5
A update() 0 46 5
B fileDestroy() 0 49 6
B store() 0 56 6
A downloadProduct() 0 21 3

How to fix   Complexity   

Complex Class

Complex classes like ProductController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProductController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Product;
4
5
// use Illuminate\Http\Request;
6
    use App\Model\Order\Order;
7
    use App\Model\Payment\Currency;
8
    use App\Model\Payment\Period;
9
    use App\Model\Payment\Plan;
10
    use App\Model\Payment\Tax;
11
    use App\Model\Payment\TaxClass;
12
    use App\Model\Payment\TaxProductRelation;
13
    use App\Model\Product\Price;
14
    use App\Model\Product\Product;
15
    use App\Model\Product\ProductGroup;
16
    use App\Model\Product\ProductUpload;
17
    use App\Model\Product\Subscription;
18
    use App\Model\Product\Type;
19
    use Bugsnag\BugsnagLaravel\Facades\Bugsnag;
20
    use Illuminate\Http\Request;
21
    use Illuminate\Support\Facades\Input;
22
    use Spatie\Activitylog\Models\Activity;
23
24
    // use Input;
25
26
    class ProductController extends BaseProductController
27
    {
28
        public $product;
29
        public $price;
30
        public $type;
31
        public $subscription;
32
        public $currency;
33
        public $group;
34
        public $plan;
35
        public $tax;
36
        public $tax_relation;
37
        public $tax_class;
38
        public $product_upload;
39
40
        public function __construct()
41
        {
42
            $this->middleware('auth');
43
            $this->middleware('admin', ['except' => ['adminDownload', 'userDownload']]);
44
45
            $product = new Product();
46
            $this->product = $product;
47
48
            $price = new Price();
49
            $this->price = $price;
50
51
            $type = new Type();
52
            $this->type = $type;
53
54
            $subscription = new Subscription();
55
            $this->subscription = $subscription;
56
57
            $currency = new Currency();
58
            $this->currency = $currency;
59
60
            $group = new ProductGroup();
61
            $this->group = $group;
62
63
            $plan = new Plan();
64
            $this->plan = $plan;
65
66
            $tax = new Tax();
67
            $this->tax = $tax;
68
69
            $period = new Period();
70
            $this->period = $period;
71
72
            $tax_relation = new TaxProductRelation();
73
            $this->tax_relation = $tax_relation;
74
75
            $tax_class = new TaxClass();
76
            $this->tax_class = $tax_class;
77
78
            $product_upload = new ProductUpload();
79
            $this->product_upload = $product_upload;
80
        }
81
82
        /**
83
         * Display a listing of the resource.
84
         *
85
         * @return \Response
86
         */
87
        public function index()
88
        {
89
            try {
90
                return view('themes.default1.product.product.index');
91
            } catch (\Exception $e) {
92
                Bugsnag::notifyException($e);
93
94
                return redirect('/')->with('fails', $e->getMessage());
95
            }
96
        }
97
98
        /**
99
         * Display a listing of the resource.
100
         *
101
         * @return \Response
102
         */
103
        public function getProducts()
104
        {
105
            try {
106
                $new_product = Product::select('id', 'name', 'type', 'group')->get();
107
108
                return\ DataTables::of($new_product)
109
110
                            ->addColumn('checkbox', function ($model) {
111
                                return "<input type='checkbox' class='product_checkbox' 
112
                                value=".$model->id.' name=select[] id=check>';
113
                            })
114
                            ->addColumn('name', function ($model) {
115
                                return ucfirst($model->name);
116
                            })
117
                            ->addColumn('type', function ($model) {
118
                                 if ($this->type->where('id', $model->type)->first()) {
119
                                    return $this->type->where('id', $model->type)->first()->name;
120
                                } else {
121
                                    return 'Not available';
122
                                }
123
                            })
124
                            ->addColumn('group', function ($model) {
125
                                if ($this->group->where('id', $model->group)->first()) {
126
                                    return $this->group->where('id', $model->group)->first()->name;
127
                                } else {
128
                                    return 'Not available';
129
                                }
130
                            })
131
                            ->addColumn('price', function ($model) {
132
                                if ($this->price->where('product_id', $model->id)->first()) {
133
                                    return $this->price->where('product_id', $model->id)->first()->price;
134
                                } else {
135
                                    return 'Not available';
136
                                }
137
                            })
138
                            ->addColumn('currency', function ($model) {
139
                                if ($this->price->where('product_id', $model->id)->first()) {
140
                                    return $this->price->where('product_id', $model->id)->first()->currency;
141
                                } else {
142
                                    return 'Not available';
143
                                }
144
                            })
145
                            ->addColumn('Action', function ($model) {
146
                                $url = '';
147
                                if ($model->type == 2) {
148
                                    $url = '<a href='.url('product/download/'.$model->id).
149
                                    " class='btn btn-sm btn-primary btn-xs'><i class='fa fa-download' 
150
                                    style='color:white;'> </i>&nbsp;&nbsp;Download</a>";
151
                                }
152
153
                                return '<p><a href='.url('products/'.$model->id.'/edit').
154
                                " class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit'
155
                                 style='color:white;'> </i>&nbsp;&nbsp;Edit</a>&nbsp;$url</p>";
156
                            })
157
158
                            ->rawColumns(['checkbox', 'name', 'type', 'group', 'price', 'currency', 'Action'])
159
                            ->make(true);
160
            } catch (\Exception $e) {
161
                Bugsnag::notifyException($e);
162
163
                return redirect()->back()->with('fails', $e->getMessage());
164
            }
165
        }
166
167
168
169
        // Save file Info in Modal popup
170
        public function save(Request $request)
171
        {
172
            try {
173
                $product_id = Product::where('name', '=', $request->input('product'))->select('id')->first();
174
175
                $this->product_upload->product_id = $product_id->id;
176
                $this->product_upload->title = $request->input('title');
177
                $this->product_upload->description = $request->input('description');
178
                $this->product_upload->version = $request->input('version');
179
180
                if ($request->file) {
181
                    $file = $request->file('file')->getClientOriginalName();
182
183
                    $destination = storage_path().'/products';
184
                    $request->file('file')->move($destination, $file);
185
                    $this->product_upload->file = $file;
186
                }
187
                $this->product_upload->save();
188
189
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
190
            } catch (\Exception $e) {
191
                Bugsnag::notifyException($e);
192
193
                return redirect()->with('fails', $e->getMessage());
194
            }
195
        }
196
197
       
198
        /**
199
         * Show the form for creating a new resource.
200
         *
201
         * @return \Response
202
         */
203
        public function create()
204
        {
205
            try {
206
                /*
207
                 * server url
208
                 */
209
                $url = $this->getMyUrl();
210
                $i = $this->product->orderBy('created_at', 'desc')->first()->id + 1;
211
                $cartUrl = $url.'/pricing?id='.$i;
212
                $type = $this->type->pluck('name', 'id')->toArray();
213
                $subscription = $this->plan->pluck('name', 'id')->toArray();
214
                $currency = $this->currency->pluck('name', 'code')->toArray();
215
                $group = $this->group->pluck('name', 'id')->toArray();
216
                $products = $this->product->pluck('name', 'id')->toArray();
217
                $periods = $this->period->pluck('name', 'days')->toArray();
218
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
219
220
                return view('themes.default1.product.product.create',
221
                    compact('subscription', 'type', 'periods', 'currency',
222
                        'group', 'cartUrl', 'products', 'taxes'));
223
            } catch (\Exception $e) {
224
                Bugsnag::notifyException($e);
225
226
                return redirect()->back()->with('fails', $e->getMessage());
227
            }
228
        }
229
230
        /**
231
         * Store a newly created resource in storage.
232
         *
233
         * @return \Response
234
         */
235
        public function store(Request $request)
236
        {
237
            $input = $request->all();
238
            // dd($input);
239
            $v = \Validator::make($input, [
240
                        'name'       => 'required|unique:products,name',
241
                        'type'       => 'required',
242
                        'group'      => 'required',
243
                        'description'=> 'required',
244
                        'image'      => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
245
                        // 'version' => 'required',
246
            ]);
247
            if ($v->fails()) {
248
                //     $currency = $input['currency'];
249
250
                return redirect()->back()
251
                        ->withErrors($v)
252
                        ->withInput()
253
                        ->with('currency');
254
            }
255
256
            try {
257
                if ($request->hasFile('image')) {
258
                    $image = $request->file('image')->getClientOriginalName();
259
                    $imagedestinationPath = 'dist/product/images';
260
                    $request->file('image')->move($imagedestinationPath, $image);
261
                    $this->product->image = $image;
262
                }
263
264
                $product = $this->product;
265
                $product->fill($request->except('image', 'file'))->save();
266
                // Product::where('id',$product->id)->update(['name'=>$request->names]);
267
268
                $product_id = $product->id;
269
                $subscription = $request->input('subscription');
270
271
                $price = $request->input('price');
272
                // $price=
273
274
                $sales_price = $request->input('sales_price');
275
                $currencies = $request->input('currency');
276
                $taxes = $request->input('tax');
277
                if ($taxes) {
278
                    foreach ($taxes as $key=>$value) {
279
                        $newtax = new TaxProductRelation();
280
                        $newtax->product_id = $product_id;
281
                        $newtax->tax_class_id = $value;
282
                        $newtax->save();
283
                    }
284
                }
285
286
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
287
            } catch (\Exception $e) {
288
                Bugsnag::notifyException($e);
289
290
                return redirect()->with('fails', $e->getMessage());
291
            }
292
        }
293
294
        /**
295
         * Show the form for editing the specified resource.
296
         *
297
         * @param int $id
298
         *
299
         * @return \Response
300
         */
301
        public function edit($id)
302
        {
303
            try {
304
                $type = $this->type->pluck('name', 'id')->toArray();
305
306
                $subscription = $this->plan->pluck('name', 'id')->toArray();
307
                $currency = $this->currency->pluck('name', 'code')->toArray();
308
                $group = $this->group->pluck('name', 'id')->toArray();
309
                $products = $this->product->pluck('name', 'id')->toArray();
310
                $periods = $this->period->pluck('name', 'days')->toArray();
311
                $url = $this->GetMyUrl();
312
                $cartUrl = $url.'/cart?id='.$id;
313
                $product = $this->product->where('id', $id)->first();
314
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
315
                // dd($taxes);
316
                $saved_taxes = $this->tax_relation->where('product_id', $id)->get();
317
                $savedTaxes = $this->tax_relation->where('product_id', $id)->pluck('tax_class_id')->toArray();
318
319
                return view('themes.default1.product.product.edit',
320
                    compact('product', 'periods', 'type', 'subscription',
321
                        'currency', 'group', 'price', 'cartUrl', 'products',
322
                        'regular', 'sales', 'taxes', 'saved_taxes', 'savedTaxes'));
323
            } catch (\Exception $e) {
324
                Bugsnag::notifyException($e);
325
326
                return redirect()->back()->with('fails', $e->getMessage());
327
            }
328
        }
329
330
        /**
331
         * Update the specified resource in storage.
332
         *
333
         * @param int $id
334
         *
335
         * @return \Response
336
         */
337
        public function update($id, Request $request)
338
        {
339
            $input = $request->all();
340
            $v = \Validator::make($input, [
341
                        'name'    => 'required',
342
                        'type'    => 'required',
343
                        'group'   => 'required',
344
                        'image'   => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
345
      ]);
346
347
            if ($v->fails()) {
348
                return redirect()->back()->with('errors', $v->errors());
349
            }
350
351
            try {
352
                $product = $this->product->where('id', $id)->first();
353
                if ($request->hasFile('image')) {
354
                    $image = $request->file('image')->getClientOriginalName();
355
                    $imagedestinationPath = 'dist/product/images';
356
                    $request->file('image')->move($imagedestinationPath, $image);
357
                    $product->image = $image;
358
                }
359
                if ($request->hasFile('file')) {
360
                    $file = $request->file('file')->getClientOriginalName();
361
                    $filedestinationPath = storage_path().'/products';
362
                    $request->file('file')->move($filedestinationPath, $file);
363
                    $product->file = $file;
364
                }
365
                $product->fill($request->except('image', 'file'))->save();
366
                $this->updateVersionFromGithub($product->id);
367
368
                $product_id = $product->id;
369
                $subscription = $request->input('subscription');
370
                $cost = $request->input('price');
371
                $sales_price = $request->input('sales_price');
372
                $currencies = $request->input('currency');
373
374
                //add tax class to tax_product_relation table
375
                $taxes = $request->input('tax');
376
                $newTax = $this->saveTax($taxes, $product_id);
377
378
                return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
379
            } catch (\Exception $e) {
380
                Bugsnag::notifyException($e);
381
382
                return redirect()->back()->with('fails', $e->getMessage());
383
            }
384
        }
385
386
       
387
388
        /**
389
         * Remove the specified resource from storage.
390
         *
391
         * @param int $id
392
         *
393
         * @return \Response
394
         */
395
        public function destroy(Request $request)
396
        {
397
            try {
398
                $ids = $request->input('select');
399
                if (!empty($ids)) {
400
                    foreach ($ids as $id) {
401
                        if ($id != 1) {
402
                            $product = $this->product->where('id', $id)->first();
403
                            if ($product) {
404
                                $product->delete();
405
                            } else {
406
                                echo "<div class='alert alert-danger alert-dismissable'>
407
                    <i class='fa fa-ban'></i>
408
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
409
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
410
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
411
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
412
                </div>';
413
                                //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
414
                            }
415
                            echo "<div class='alert alert-success alert-dismissable'>
416
                    <i class='fa fa-ban'></i>
417
                    <b>"./* @scrutinizer ignore-type */
418
                    \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */ \Lang::get('message.success').'
419
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
420
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
421
                </div>';
422
                        } else {
423
                            echo "<div class='alert alert-danger alert-dismissable'>
424
                    <i class='fa fa-ban'></i>
425
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
426
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
427
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
428
                        './* @scrutinizer ignore-type */ \Lang::get('message.can-not-delete-default').'
429
                </div>';
430
                        }
431
                    }
432
                } else {
433
                    echo "<div class='alert alert-danger alert-dismissable'>
434
                    <i class='fa fa-ban'></i>
435
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
436
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
437
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
438
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
439
                </div>';
440
                    //echo \Lang::get('message.select-a-row');
441
                }
442
                $lastActivity = Activity::all()->last();
443
            } catch (\Exception $e) {
444
                echo "<div class='alert alert-danger alert-dismissable'>
445
                    <i class='fa fa-ban'></i>
446
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
447
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
448
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
449
                        '.$e->getMessage().'
450
                </div>';
451
            }
452
        }
453
454
        /**
455
         * Remove the specified resource from storage.
456
         *
457
         * @param int $id
458
         *
459
         * @return \Response
460
         */
461
        public function fileDestroy(Request $request)
462
        {
463
            try {
464
                $ids = $request->input('select');
465
                if (!empty($ids)) {
466
                    foreach ($ids as $id) {
467
                        if ($id != 1) {
468
                            $product = $this->product_upload->where('id', $id)->first();
469
                            if ($product) {
470
                                $product->delete();
471
                            } else {
472
                                echo "<div class='alert alert-danger alert-dismissable'>
473
                    <i class='fa fa-ban'></i>
474
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
475
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
476
                        '.\Lang::get('message.no-record').'
477
                </div>';
478
                                //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
479
                            }
480
                            echo "<div class='alert alert-success alert-dismissable'>
481
                    <i class='fa fa-ban'></i>
482
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.success').'
483
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
484
                        '.\Lang::get('message.deleted-successfully').'
485
                </div>';
486
                        } else {
487
                            echo "<div class='alert alert-danger alert-dismissable'>
488
                    <i class='fa fa-ban'></i>
489
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
490
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
491
                        '.\Lang::get('message.can-not-delete-default').'
492
                </div>';
493
                        }
494
                    }
495
                } else {
496
                    echo "<div class='alert alert-danger alert-dismissable'>
497
                    <i class='fa fa-ban'></i>
498
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
499
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
500
                        '.\Lang::get('message.select-a-row').'
501
                </div>';
502
                    //echo \Lang::get('message.select-a-row');
503
                }
504
            } catch (\Exception $e) {
505
                echo "<div class='alert alert-danger alert-dismissable'>
506
                    <i class='fa fa-ban'></i>
507
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
508
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
509
                        '.$e->getMessage().'
510
                </div>';
511
            }
512
        }
513
514
        /*
515
        *  Download Files from Filesystem/Github
516
        */
517
        public function downloadProduct($uploadid, $id, $invoice_id, $version_id = '')
518
        {
519
            try {
520
                $product = $this->product->findOrFail($uploadid);
521
                $type = $product->type;
522
                $owner = $product->github_owner;
523
                $repository = $product->github_repository;
524
                $file = $this->product_upload
525
                ->where('product_id', '=', $uploadid)
526
                ->where('id', $version_id)->select('file')->first();
527
                $order = Order::where('invoice_id', '=', $invoice_id)->first();
528
                $order_id = $order->id;
529
                if ($type == 2) {
530
                    $relese = $this->getRelease($owner, $repository, $order_id, $file);
531
532
                    return $relese;
533
                }
534
            } catch (\Exception $e) {
535
                Bugsnag::notifyException($e);
536
537
                return redirect()->back()->with('fails', $e->getMessage());
538
            }
539
        }
540
541
        public function adminDownload($id, $invoice = '', $api = false)
542
        {
543
            try {
544
                $role = \Auth::user()->role;
545
                $release = $this->getLinkToDownload($role, $invoice, $id);
546
547
                if (is_array($release) && array_key_exists('type', $release)) {
548
                    header('Location: '.$release['release']);
549
                    exit;
550
                } else {
551
                    header('Content-type: Zip');
552
                    header('Content-Description: File Transfer');
553
                    header('Content-Disposition: attachment; filename=Faveo.zip');
554
                    header('Content-Length: '.filesize($release));
555
                    flush();
556
                    readfile("$release");
557
                }
558
            } catch (\Exception $e) {
559
                if ($api) {
560
                    return response()->json(['error'=>$e->getMessage()]);
561
                }
562
                Bugsnag::notifyException($e);
563
564
                return redirect()->back()->with('fails', $e->getMessage());
565
            }
566
        }
567
568
        
569
570
        public function getSubscriptionCheckScript()
571
        {
572
            $response = "<script>
573
        function getPrice(val) {
574
            var user = document.getElementsByName('user')[0].value;
575
            var plan = '';
576
            if ($('#plan').length > 0) {
577
                var plan = document.getElementsByName('plan')[0].value;
578
            }
579
            //var plan = document.getElementsByName('plan')[0].value;
580
            //alert(user);
581
582
            $.ajax({
583
                type: 'POST',
584
                url: ".url('get-price').",
585
                data: {'product': val, 'user': user,'plan':plan},
586
                //data: 'product=' + val+'user='+user,
587
                success: function (data) {
588
                    var price = data['price'];
589
                    var field = data['field'];
590
                    $('#price').val(price);
591
                    $('#fields').append(field);
592
                }
593
            });
594
        }
595
596
    </script>";
597
        }
598
    }
599